FALLSEM2023-24 ICSE101E ELA VL2023240106565 2023-10-05 Reference-Material-I

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Dictionaries

November 24, 2023

1 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.

1.0.1 Creating Dictionaries

[31]: # Starting with Empty Dictionary


dict1 = {}
dict1['id'] = 1
dict1['name'] = 'Hello'
dict1

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

[32]: # Direct Method


dict2 = {'id':2,'name':'John'}
dict2

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

[29]: # Using List of Tuples


dict3 = dict([('id',1),('name','Donald')])
dict3

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

[30]: # Using Key-Value arguments


dict4 = dict(id=1,name='Tim')
dict4

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

1
1.0.2 Adding, Editing, Removing Elements

[10]: # adding a key/value pair


dict4['salary'] = 71500.75
dict4

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

[11]: # removing a key


del dict4['salary']
dict4

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

[12]: # updating a key


dict4['name'] = 'Tim Billy'
dict4

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

[54]: # count the number of elements


len(dict4)

[54]: 2

1.0.3 Checking for Keys

[13]: # Check if salary key exists


if 'salary' in dict4:
print(dict4['salary'])
else:
print(0)

[36]: # Better way of checking


print(dict4.get('name'))
print(dict4.get('salary')) # returns None if key is not present

Tim
None

1.0.4 Looping Techniques

[18]: # Default Method


for key in dict4:
print(dict4[key])

2
1
Tim Billy

[19]: # Using Keys Method


for key in dict4.keys():
print(dict4[key])

1
Tim Billy

[20]: # Using Values Method


for value in dict4.values():
print(value)

1
Tim Billy

[21]: # Using Items Method


for k,v in dict4.items():
print('{}:{}'.format(k,v))

id:1
name:Tim Billy

1.0.5 Dictionary Comprehensions

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

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

1.0.6 Dictionary Methods

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

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


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

[42]: # merge 2 dictionaries


knowledge = {"Frank": {"Perl"}, "Monica":{"C","C++"}}
knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl", "Python"}}
knowledge.update(knowledge2)
knowledge

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

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


{}

1.0.7 Lists to Dictionaries


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

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

1.0.8 Dictionary with other Data Types

[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')

You might also like