Dictionaries
Dictionaries¶
- Dictionaries are used to store data values in key:value pairs.
Creating and Accessing Dictionary¶
In [1]:
Copied!
person = {
'name': 'Alice',
'age': 25
}
print(person['name']) # Accessing value by key
person = {
'name': 'Alice',
'age': 25
}
print(person['name']) # Accessing value by key
Alice
Adding, Updating, and Removing Elements¶
In [13]:
Copied!
## add city
person['city'] = 'Kathmandu'
## update age
person['age'] = 50
print(person)
## add city
person['city'] = 'Kathmandu'
## update age
person['age'] = 50
print(person)
{'name': 'Alice', 'age': 50, 'city': 'Kathmandu'}
In [14]:
Copied!
## delete name
del person['name']
print(person)
## delete name
del person['name']
print(person)
{'age': 50, 'city': 'Kathmandu'}
Dictionary Methods¶
Method | Description | Example Code | Output |
---|---|---|---|
keys() |
Returns a list of dictionary keys | d = {'a': 1} d.keys() |
dict_keys(['a']) |
values() |
Returns a list of dictionary values | d = {'a': 1} d.values() |
dict_values([1]) |
items() |
Returns a list of key-value tuple pairs | d = {'a': 1} d.items() |
dict_items([('a', 1)]) |
get() |
Returns value for key if key exists | d = {'a': 1} d.get('a') |
1 |
update() |
Updates dictionary with another dictionary | d.update({'b': 2}) |
{'a': 1, 'b': 2} |
pop() |
Removes and returns value for key | d.pop('a') |
1 and {'b': 2} |
clear() |
Removes all items | d.clear() |
{} |
Exercise Create a dictionary with movie data (title, year, rating)¶
Tasks:
- Access the title.
- Update the rating.
- Add a new key: 'actor'.
- Delete the year.
- Print all keys and values.
In [2]:
Copied!
print(person)
print(person)
{'name': 'Alice', 'age': 25}
In [3]:
Copied!
person.keys()
person.keys()
Out[3]:
dict_keys(['name', 'age'])
In [4]:
Copied!
person.values()
person.values()
Out[4]:
dict_values(['Alice', 25])
In [5]:
Copied!
person.items()
person.items()
Out[5]:
dict_items([('name', 'Alice'), ('age', 25)])
In [6]:
Copied!
person
person
Out[6]:
{'name': 'Alice', 'age': 25}
In [7]:
Copied!
person['location']
person['location']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[7], line 1 ----> 1 person['location'] KeyError: 'location'
In [9]:
Copied!
person.get('name')
person.get('name')
Out[9]:
'Alice'
In [11]:
Copied!
person.get('location', 'Kathmandu')
person.get('location', 'Kathmandu')
Out[11]:
'Kathmandu'
In [12]:
Copied!
person.get('dsafaskhj', 'Kathmandu')
person.get('dsafaskhj', 'Kathmandu')
Out[12]:
'Kathmandu'
type casting¶
In [14]:
Copied!
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
my_list.append(5)
my_tuple = tuple(my_list)
print(my_tuple)
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
my_list.append(5)
my_tuple = tuple(my_list)
print(my_tuple)
(1, 2, 3, 4, 5)
In [ ]:
Copied!