Python Dictionary

Table of Contents

What is Dictionary in python ?

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)

How to create a dictionary ?

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)])

Access values from python dictionary

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"))
pythoneasy
2016

When there is no value present corresponding to the key, using square bracket KeyError is raised by python
But using get(), it does not through error unless it prints None
using square bracket []
d = {"website": "pythoneasy", "year":2016}
print(d["domain"]) # 'domain' key is not available

Traceback (most recent call last): File "D:/pythoneasy/test3.py", line 2, in<module> print(d["domain"]) KeyError: 'domain'

using square get() function

d = {"website": "pythoneasy", "year": 2016}
print(d.get("domain"))
None

Update and add elements to dictionary

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'}

{'website': 'python.org', 'year': 2016}
{'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

Membership test in dictionary

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
True
True
False

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)
False
False

How to iterate through a dictionary

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)
website
year

We can use key to fetch the corresponding value
Example:
d = {"website": "pythoneasy", "year": 2016}
for var in d:
    print("key is -", var, ", value is -", d[var])
key is - website , value is - pythoneasy
key is - year , value is - 2016

Dictionary comprehension:

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)
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

Example 2: (Using zip)
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)
{'name': 'John', 'age': 25, 'mark': 45.7, 'lang':'english'}

Example 3 : (from another dictionary)
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)
{'name': 'John', 'age': 25, 'mark': 45.7, 'lang':'english'}

Python List methods

Python has a set of built-in methods that you can use on dictionary
These are the operations that dictionaries support
Example:
>>> 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
Example:
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_2 = dict_1.copy()
>>> dict_2
{'name': 'pythoneasy', 'year': 2016}
Example:
{'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'
>>>
Example:
>>> 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)]
>>>
Example:
>>> 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']
If default is not given and key is not in the dictionary, a KeyError is raised
Example:
>>> 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'
>>>
Pairs are returned in LIFO order
Example:
>>> 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'
default defaults to None
Example:
>>> 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}
Example:
>>> dict_1 = {'name':'pythoneasy', 'year':2016}
>>> dict_2 = {'lang': 'english'}
>>> dict_1.update(dict_2)
>>> dict_1
{'name': 'pythoneasy', 'year': 2016, 'lang': 'english'}
Example:
>>> 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]
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description