Dictionaries

Dictionaries are unordered set of key value pairs separated by commas. Unlike Lists (which are sequence based) dictionary elements are not indexed but can be retrieved using the keys.

Creating Dictionaries


In [31]:
# Starting with Empty Dictionary
dict1 = {}
dict1['id'] = 1
dict1['name'] = 'Hello'
dict1


Out[31]:
{'id': 1, 'name': 'Hello'}

In [32]:
# Direct Method
dict2 = {'id':2,'name':'John'}
dict2


Out[32]:
{'id': 2, 'name': 'John'}

In [29]:
# Using List of Tuples
dict3 = dict([('id',1),('name','Donald')])
dict3


Out[29]:
{'id': 1, 'name': 'Donald'}

In [30]:
# Using Key-Value arguments
dict4 = dict(id=1,name='Tim')
dict4


Out[30]:
{'id': 1, 'name': 'Tim'}

Adding, Editing, Removing Elements


In [10]:
# adding a key/value pair
dict4['salary'] = 71500.75
dict4


Out[10]:
{'id': 1, 'name': 'Tim', 'salary': 71500.75}

In [11]:
# removing a key
del dict4['salary']
dict4


Out[11]:
{'id': 1, 'name': 'Tim'}

In [12]:
# updating a key
dict4['name'] = 'Tim Billy'
dict4


Out[12]:
{'id': 1, 'name': 'Tim Billy'}

In [54]:
# count the number of elements
len(dict4)


Out[54]:
2

Checking for Keys


In [13]:
# Check if salary key exists
if 'salary' in dict4:
    print(dict4['salary'])
else:
    print(0)


0

In [36]:
# Better way of checking
print(dict4.get('name'))
print(dict4.get('salary')) # returns None if key is not present


Tim
None

Looping Techniques


In [18]:
# Default Method
for key in dict4:
    print(dict4[key])


1
Tim Billy

In [19]:
# Using Keys Method
for key in dict4.keys():
    print(dict4[key])


1
Tim Billy

In [20]:
# Using Values Method
for value in dict4.values():
    print(value)


1
Tim Billy

In [21]:
# Using Items Method
for k,v in dict4.items():
    print('{}:{}'.format(k,v))


id:1
name:Tim Billy

Dictionary Comprehensions


In [22]:
{x: x**2 for x in range(10)}


Out[22]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Dictionary Methods


In [44]:
# copy
dict5 = dict4.copy()
dict5['name']='Billy John'
print(dict4)
print(dict5)


{'id': 1, 'name': 'Tim'}
{'id': 1, 'name': 'Billy John'}

In [42]:
# merge 2 dictionaries
knowledge = {"Frank": {"Perl"}, "Monica":{"C","C++"}}
knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl", "Python"}}
knowledge.update(knowledge2)
knowledge


Out[42]:
{'Frank': {'Perl', 'Python'}, 'Guido': {'Python'}, 'Monica': {'C', 'C++'}}

In [41]:
# remove all elements from the dictionary

print(dict1)
dict1.clear()
print(dict1) # pls note dictionary is not deleted but only emptied


{'id': 1, 'name': 'Hello'}
{}

Lists to Dictionaries


In [51]:
countries = ['United States','England','France','India']
capitals = ['Washington','London','Paris','New Delhi']
country_capital_zip = zip(countries,capitals) # returns list iterator
print(dict(country_capital_zip))
country_capitals = list(zip(countries,capitals))
print(country_capitals)
print(dict(country_capitals))


{'United States': 'Washington', 'England': 'London', 'France': 'Paris', 'India': 'New Delhi'}
[('United States', 'Washington'), ('England', 'London'), ('France', 'Paris'), ('India', 'New Delhi')]
{'United States': 'Washington', 'England': 'London', 'France': 'Paris', 'India': 'New Delhi'}

In [52]:
# combined to single step
country_specialities_dict = dict(list(zip(["pizza", "sauerkraut", "paella", "hamburger"], ["Italy", "Germany", "Spain", "USA"," Switzerland"])))
print(country_specialities_dict)


{'pizza': 'Italy', 'sauerkraut': 'Germany', 'paella': 'Spain', 'hamburger': 'USA'}

Dictionary with other Data Types


In [4]:
dict6 = {'name':'Alex','favorite_colors':['Blue','Red'],'contacts':{'email':'alex@example.com','phone':'123-456-7890'},'nick_names':('Alexie','A-man')}
dict6
print(dict6['favorite_colors'])
print(dict6['contacts']['email'])
print(dict6['nick_names'])


['Blue', 'Red']
alex@example.com
('Alexie', 'A-man')