Dictionaries are unordered data structures that map unique keys to values. Dictionary keys can be any immutable data type like numbers, strings, tuples, and etc, while values can be integers, lists, functions, strings, etc.
For example, here we have a dayDict which has ints as keys and strings as values
dayDict = {
1: 'Mon',
2: 'Tue',
3: 'Wed',
4: 'Thu',
5: 'Fri',
6: 'Sat',
7: 'Sun'
}
Important thing to know, if you are using a mutable data type like list as a key, you will get an error, example
myDict = {
1: 'This can be a key',
'key': 'This can be a key',
(1, 2, 3): 'This can be a key',
[1, 2, 3]: 'You will get an error with this'
}
12.1 Accessing Values in a Dictionary
To access a dictionary value, you can use square brackets. Example
person = {
'name': 'Jack',
'age': 23,
}
print(person['name']) # Jack
print(person['age']) # 23
But when you trying to access a not existed key, you will get KeyError, example
person = {
'name': 'Jack',
'age': 23,
}
print(person['name']) # Jack
print(person['age']) # 23
print(person['first_name'])
This will produce KeyError.
Traceback (most recent call last):
File ".\example.py", line 30, in <module>
print(person['first_name'])
KeyError: 'first_name'
12.2 Update a Dictionary
Things that you can update with a dictionary are adding a new key, change the value of specific key, and using del keyword to delete specific key, example
person = {
'name': 'Jack Sparrow',
'age': 23
}
# add key 'first_name'
person['first_name'] = 'Jack'
person['last_name'] = 'Sparrow'
# update the value age
person['age'] = 46
# delete 'name' key
del person['name']
print(person)
12.3 Dictionary Operations
Some operations that you can do with a dictionary.
person = {
'first_name': 'Jack',
'last_name': 'Sparrow',
'age': 23,
'city': 'Caribbean'
}
# len(dict) return the number of (key, value) pairs.
print(len(person)) # 4
print('city' in person) # True
print('name' not in person) # True
12.4 Iterate the Dictionary
You can iterate the keys of a dictionary with for loop, example
for p in person:
print(p)
You can also iterate the keys of a dictionary with keys() method.
for pKey in person.keys():
print(pKey)
To iterate the values of a dictionary you can use values() method.
for pVal in person.values():
print(pVal)
And you can use items() method to iterate the keys and values of a dictionary at once.
for key, val in person.items():
print(str(key)+ ' => ' +str(val))
I Think that's all about Python dictionaries, if you guys have any questions please give comments below.
0 Response to "12. Python Dictionaries"
Post a Comment