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.
In [31]:
# Starting with Empty Dictionary
dict1 = {}
dict1['id'] = 1
dict1['name'] = 'Hello'
dict1
Out[31]:
In [32]:
# Direct Method
dict2 = {'id':2,'name':'John'}
dict2
Out[32]:
In [29]:
# Using List of Tuples
dict3 = dict([('id',1),('name','Donald')])
dict3
Out[29]:
In [30]:
# Using Key-Value arguments
dict4 = dict(id=1,name='Tim')
dict4
Out[30]:
In [10]:
# adding a key/value pair
dict4['salary'] = 71500.75
dict4
Out[10]:
In [11]:
# removing a key
del dict4['salary']
dict4
Out[11]:
In [12]:
# updating a key
dict4['name'] = 'Tim Billy'
dict4
Out[12]:
In [54]:
# count the number of elements
len(dict4)
Out[54]:
In [13]:
# Check if salary key exists
if 'salary' in dict4:
print(dict4['salary'])
else:
print(0)
In [36]:
# Better way of checking
print(dict4.get('name'))
print(dict4.get('salary')) # returns None if key is not present
In [18]:
# Default Method
for key in dict4:
print(dict4[key])
In [19]:
# Using Keys Method
for key in dict4.keys():
print(dict4[key])
In [20]:
# Using Values Method
for value in dict4.values():
print(value)
In [21]:
# Using Items Method
for k,v in dict4.items():
print('{}:{}'.format(k,v))
In [22]:
{x: x**2 for x in range(10)}
Out[22]:
In [44]:
# copy
dict5 = dict4.copy()
dict5['name']='Billy John'
print(dict4)
print(dict5)
In [42]:
# merge 2 dictionaries
knowledge = {"Frank": {"Perl"}, "Monica":{"C","C++"}}
knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl", "Python"}}
knowledge.update(knowledge2)
knowledge
Out[42]:
In [41]:
# remove all elements from the dictionary
print(dict1)
dict1.clear()
print(dict1) # pls note dictionary is not deleted but only emptied
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))
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)
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'])