A dictionary in Python is a collection of unordered series of “key: value” pairs
Dictionary
keys should be unique and immutable types (like string, numbers or tuple - which are also
known as hashable type https://docs.python.org/3/glossary.html#term-hashable)
Dictionaries are coded in curly braces using key value pairs.
The keys should be unique and
hashable (immutable) types
Dictionaries can also be created using a built in
function dict()
Example:
# Empty dictionary
d = {}
d = dict() # using built-in function
# strings as keys
d = {"website": "pythoneasy", "year": 2016} # website, year are the keys and pythoneasy, 2016 are the values
d = dict(website="pythoneasy", year=2016) # using built-in function
# numbers as keys
d = {1: "pythoneasy", 2: 2016, 3: 166712}
# Tuples as keys
d = {(1, 2): "pythoneasy", (4,2): 2016} # Here (1, 2) and (4,2) are keys
# sequencies as keys
# Each items as a key , value pair. 1 and 2 are the keys 'pythoneasy' and 2016 are values
d = dict([(1, 'pythoneasy'), (2, 2016)])
We can use keys to access the values of dictionary with square brackets [] or get() functions
d = {"website": "pythoneasy", "year": 2016}
print(d["website"])
print(d.get("year"))
d = {"website": "pythoneasy", "year":2016}
print(d["domain"]) # 'domain' key is not available
using square get() function
d = {"website": "pythoneasy", "year": 2016}
print(d.get("domain"))
As dictionary as mutable we can change and add new values to dictionary
Using assignment
operator and the dictionary name we can update an existing value or add new value with a key
d = {"website": "pythoneasy", "year": 2016}
# Change the value of key "website"
d["website"] = "python.org"
print(d) # prints {'website': 'python.org', 'year': 2016}
# Add a new value "english" with key "language"
d["language"] = "english"
print(d) # prints {'website': 'python.org', 'year': 2016, 'language': 'english'}
The value for key "website" is updated and a new value for the key "language"
is created as the key is not available in d
We can check a key is available in the dictionary or not using in operator
d = {"website": "pythoneasy", "year": 2016}
print("website" in d) # prints True as "website" is a key
print("year" in d) # prints True as "year" is a key
print("language" in d) # prints True as "language" is not a key
Only keys can be checked inside a dictionary not values
For example "pythoneasy"
is available as value inside the dictionary "d", but membership test will
print False
d = {"website": "pythoneasy", "year": 2016}
print("pythoneasy" in d)
print(2016 in d)
We can iterate though a dictionary simply by using a for loop.
When a
dictionary is used as iterable, only the keys are appeared as
element.
Example:
d = {"website": "pythoneasy", "year": 2016}
for var in d:
print(var)
d = {"website": "pythoneasy", "year": 2016}
for var in d:
print("key is -", var, ", value is -", d[var])
Dictionary comprehension expressions are used to create a new dictionary at the runtime from another iterator object.
Syntax{key: value for (key, value) in iterable}
Example 1 (From an iterable):
tuple_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
dict_1 = {item: item * 2 for item in tuple_1}
print(dict_1)
list_1 = ['name', 'age', 'mark', 'lang']
tuple_1 = ('John', 25, 45.7, 'english')
dict_1 = {key: value for key, value in zip(list_1, tuple_1)}
print(dict_1)
dict_1 = {'name': 'John', 'age': 25, 'mark': 45.7, 'lang': 'english'}
dict_2 = {key: value for key, value in dict_1.items()}
print(dict_2)
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_1
{'name': 'pythoneasy', 'year': 2016}
>>> dict_1.clear()
>>> dict_1
{}
dict_1.clear()
removes all the element from dict_1
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_2 = dict_1.copy()
>>> dict_2
{'name': 'pythoneasy', 'year': 2016}
{'name': 'pythoneasy', 'year': 2016}
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_1.get('year')
2016
>>> print(dict_1.get('language')) # key 'language' not available, so None is returned
None
>>> dict_1.get('language', 'english') # key 'language' not available, so default value 'english' is returned
'english'
>>>
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_1.items()
dict_items([('name', 'pythoneasy'), ('year', 2016)])
>>> type(dict_1.items())
<class 'dict_items'>
>>> list(dict_1.items()) # convert to list
[('name', 'pythoneasy'), ('year', 2016)]
>>>
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_1.keys()
dict_keys(['name', 'year'])
>>> type(dict_1.keys())
<class 'dict_keys'>
>>> list(dict_1.keys())
['name', 'year']
>>> dict_1 = {'name': 'pythoneasy', 'year': 2016, 'lang': 'english'}
>>> dict_1.pop('lang')
'english'
>>> dict_1 # 'lang' is removed
{'name': 'pythoneasy', 'year': 2016}
>>> dict_1.pop('lang', 'french') # 'lang' is removed already, so default 'french' will be printed
'french'
>>> dict_1.pop('lang') # key 'lang' not present and default not provided
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'lang'
>>>
>>> dict_1 = {'name': 'pythoneasy', 'year': 2016, 'lang': 'english'}
>>> dict_1.popitem()
('lang', 'english')
>>> dict_1.popitem()
('name', 'pythoneasy')
>>> dict_1.popitem()
('year', 2016)
>>> dict_1.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'
>>> dict_1 = {'name': 'pythoneasy', 'year': 2016}
>>> dict_1.setdefault('name', 'python.org')
'pythoneasy'
>>> dict_1
{'name': 'pythoneasy', 'year': 2016}
>>> dict_1.setdefault('new_name', 'python.org')
'python.org'
>>> dict_1
{'new_name': 'python.org', 'name': 'pythoneasy', 'year': 2016}
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_2 = {'lang': 'english'}
>>> dict_1.update(dict_2)
>>> dict_1
{'name': 'pythoneasy', 'year': 2016, 'lang': 'english'}
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_1.values()
dict_values(['pythoneasy', 2016])
>>> type(dict_1.values())
<class 'dict_values'>
>>> list(dict_1.values())
['pythoneasy', 2016]