Dictionary

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

keyboard_arrow_down What is a Dictionary?

A dictionary in Python is a collection of key-value pairs.

Each key is connected to a value, and you can use a key to access the value associated with that key.
A key’s value can be a number , a string , a list , or even another dictionary .

In Python, a dictionary is wrapped in braces, {} , with a series of key-value pairs inside the braces:

dict = {
<key1>: <value1>,
<key2>: <value2>,
.
.
.
<keyN>: <valueN>
}

1 Dict = {}
2 print("Empty Dictionary: ")
3 print(Dict)

Empty Dictionary:
{}

1 Dict = dict()
2 print("Empty Dictionary: ")
3 print(Dict)

Empty Dictionary:
{}

1 thisdict = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6 print("\nDictionary with the use of String Keys: ")
7 print(thisdict)

Dictionary with the use of String Keys:


{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

1 type(thisdict)

dict
1 Dict = {1: 'Welcome', 2: 'to', 3: 'Python', 4:'Course'}
2 print("\nDictionary with the use of Integer Keys: ")
3 print(Dict)

Dictionary with the use of Integer Keys:


{1: 'Welcome', 2: 'to', 3: 'Python', 4: 'Course'}

1 d = {'1': 'Welcome' , 2: "to" , 'three': 'Uop'}


2 print("\nDictionary with the use of Mixed Keys: ")
3 print(d)

Dictionary with the use of Mixed Keys:


{'1': 'Welcome', 2: 'to', 'three': 'Uop'}

1 Dict = dict([(1, 'Hello,'), (2, 'There!')])


2 print("\nDictionary with each item as a pair: ")
3 print(Dict)

Dictionary with each item as a pair:


{1: 'Hello,', 2: 'There!'}

A dictionary is a collection which is ordered* , changeable and do not allow duplicates .

As of Python version 3.7 , dictionaries are ordered . In Python 3.6 and earlier, dictionaries are unordered .

1 dict1 = {
2 'b': 'beauty',
3 'j': 'joy',
4 'c': 'computing'
5 }
6
7 print(dict1)

{'b': 'beauty', 'j': 'joy', 'c': 'computing'}

1 #Dictionary Length
2 print("Number of elements in dict:",len(dict1))

Number of elements in dict: 3

1 dict1

{'b': 'beauty', 'j': 'joy', 'c': 'computing'}

1 # Get items
2 print("Items are ", dict1.items())

Items are dict_items([('b', 'beauty'), ('j', 'joy'), ('c', 'computing')])

1 # Get Keys
2 print("Keys are ", dict1.keys())

Keys are dict_keys(['b', 'j', 'c'])

1 # Get values
2 print("Values are ", dict1.values())

Values are dict_values(['beauty', 'joy', 'computing'])

keyboard_arrow_down Accessing Values in a Dictionary


1 dict1

{'b': 'beauty', 'j': 'joy', 'c': 'computing'}


1 dict1['b']

'beauty'

1 dict1.get('b')

'beauty'

keyboard_arrow_down Adding New Key-Value Pairs


1 dict1

{'b': 'beauty', 'j': 'joy', 'c': 'computing'}

1 dict1['a'] = 'apple'
2 dict1['z'] = "zoo"
3 print(dict1)
4 dict1['a'] = 'naa'
5 print(dict1)

{'b': 'beauty', 'j': 'joy', 'c': 'computing', 'a': 'apple', 'z': 'zoo'}
{'b': 'beauty', 'j': 'joy', 'c': 'computing', 'a': 'naa', 'z': 'zoo'}

1 dict2 = {}
2 dict2['key1'] = "value1"
3 dict2['key2'] = "value2"
4 dict2['key0'] = "value0"
5 dict2['key3'] = "value3"
6 dict2['key4'] = "value4"
7 print(dict2)

{'key1': 'value1', 'key2': 'value2', 'key0': 'value0', 'key3': 'value3', 'key4': 'value4'}

1 car = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6
7 x = car.keys()
8
9 print(x) #before the change
10
11 car["color"] = "white"
12
13 print(x) #after the change

dict_keys(['brand', 'model', 'year'])


dict_keys(['brand', 'model', 'year', 'color'])

keyboard_arrow_down Modifying Values in a Dictionary


1 dict1

{'b': 'beauty', 'j': 'joy', 'c': 'computing', 'a': 'naa', 'z': 'zoo'}

1 #Change Values
2 print("Previous value: ",dict1["a"])
3 dict1["a"] = "egg"
4 print("\nCurrent value: ",dict1["a"])

Previous value: naa

Current value: egg


1 car = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6
7 x = car.values()
8
9 print(x) #before the change
10
11 car["year"] = 2020
12
13 print(x) #after the change

dict_values(['Ford', 'Mustang', 1964])


dict_values(['Ford', 'Mustang', 2020])

keyboard_arrow_down Removing Key-Value Pairs


1 mydict = dict2.copy()
2 print(mydict)

{'key1': 'value1', 'key2': 'value2', 'key0': 'value0', 'key3': 'value3', 'key4': 'value4'}

1 mydict.pop("key2")
2 print(mydict)

{'key1': 'value1', 'key0': 'value0', 'key3': 'value3', 'key4': 'value4'}

1 mydict.popitem()
2 print(mydict)

{'key1': 'value1', 'key0': 'value0', 'key3': 'value3'}

1 mydict.popitem()
2 print(mydict)

{'key1': 'value1', 'key0': 'value0'}

1 mydict.pop()
2 print(mydict)
3 # error

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-5b0be7cee819> in <cell line: 1>()
----> 1 mydict.pop()
2 print(mydict)
3 # error

TypeError: pop expected at least 1 argument, got 0

Next steps: Explain error

1 del mydict["key0"]
2 print(mydict)

{'key1': 'value1'}

1 mydict.clear()
2 print(mydict)

{}

1 del mydict
2 print(mydict)
3 # error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-31-de386ba3d829> in <cell line: 2>()
1 del mydict
----> 2 print(mydict)
3 # error

NameError: name 'mydict' is not defined

Next steps: Explain error

keyboard_arrow_down Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword.

1 myDict = {'a':1,'b':2,'c':3,'d':4}
2
3 print(myDict)
4
5 if 'a' in myDict:
6 del myDict['a']
7
8 print(myDict)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}


{'b': 2, 'c': 3, 'd': 4}

1 thisdict = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6
7 if "model" in thisdict:
8 print("Yes, 'model' is one of the keys in the thisdict dictionary")

Yes, 'model' is one of the keys in the thisdict dictionary

keyboard_arrow_down Update Dictionary


The update() method will update the dictionary with the items from the given argument .

The argument must be a dictionary , or an iterable object with key:value pairs .

1 dict1 = {
2 'b': 'beauty',
3 'j': 'joy',
4 'c': 'computing'
5 }
6
7 dict1.update({"b": "Hi"})
8 dict1

{'b': 'Hi', 'j': 'joy', 'c': 'computing'}

1 dict1.update({"j": "There", "c": "World"})


2 dict1

{'b': 'Hi', 'j': 'There', 'c': 'World'}

If the item does not exist , the item will be added .

1 dict1.update({'p': "Python"})
2 dict1

{'b': 'Hi', 'j': 'There', 'c': 'World', 'p': 'Python'}


keyboard_arrow_down Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1 , because: dict2 will only be a reference to dict1 , and changes made in dict1
will automatically also be made in dict2 .

There are ways to make a copy , one way is to use the built-in Dictionary method copy() .

1 mydict = thisdict.copy()
2 print(mydict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Another way to make a copy is to use the built-in function dict() .

1 thisdict

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

1 mydict1 = dict(thisdict)
2 print(mydict1)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

keyboard_arrow_down Looping Through a Dictionary


keyboard_arrow_down Looping Through All Key-Value Pairs
You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

1 thisdict

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

1 for x in thisdict:
2 print(x)

brand
model
year

1 for x in thisdict:
2 print(thisdict[x])

Ford
Mustang
1964

1 thisdict.values()

dict_values(['Ford', 'Mustang', 1964])

1 for x in thisdict.values():
2 print(x)

Ford
Mustang
1964

1 for x in thisdict.keys():
2 print(x)

brand
model
year
1 for x in thisdict.items():
2 print(x)

('brand', 'Ford')
('model', 'Mustang')
('year', 1964)

1 for x, y in thisdict.items():
2 print(x,": ", y)

brand : Ford
model : Mustang
year : 1964

1 user_0 = {
2 'username': 'user_1',
3 'first': 'Ahamd',
4 'last': 'fermi',
5 'email': 'a.fermi@gmail.com'
6 }
7
8 for key, value in user_0.items():
9 print("\nKey: " + key)
10 print("Value: " + value)

Key: username
Value: user_1

Key: first
Value: Ahamd

Key: last
Value: fermi

Key: email
Value: a.fermi@gmail.com

1 favorite_languages = {
2 'jen': 'python',
3 'sarah': 'c',
4 'edward': 'ruby',
5 'phil': 'python',
6 }
7
8 for name, language in favorite_languages.items():
9 print(name.title() + "'s favorite language is " +
10 language.title() + ".")

Jen's favorite language is Python.


Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

keyboard_arrow_down Looping Through All the Keys in a Dictionary


1 for name in favorite_languages.keys():
2 print(name.title())

Jen
Sarah
Edward
Phil

keyboard_arrow_down Looping Through a Dictionary’s Keys in Order


1 favorite_languages

{'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}


1 sorted(favorite_languages.keys())

['edward', 'jen', 'phil', 'sarah']

1 for name in sorted(favorite_languages.keys()):


2 print(name.title() + ", thank you for taking the poll.")

Edward, thank you for taking the poll.


Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

keyboard_arrow_down Looping Through All Values in a Dictionary


1 print("The following languages have been mentioned:")
2 for language in favorite_languages.values():
3 print(language.title())

The following languages have been mentioned:


Python
C
Ruby
Python

keyboard_arrow_down A List in a Dictionary


1 Dict = {1: 'Geeks', 2: 'For', 3: [1, 2, 3, 4]}
2 print("\nDictionary with the use of Mixed Keys: ")
3 print(Dict)

Dictionary with the use of Mixed Keys:


{1: 'Geeks', 2: 'For', 3: [1, 2, 3, 4]}

1 favorite_languages = {
2 'jen': ['python', 'ruby'],
3 'sarah': ['c'],
4 'edward': ['ruby', 'go'],
5 'phil': ['python', 'haskell'],
6 }
7
8 for name, languages in favorite_languages.items():
9 print("\n" + name.title() + "'s favorite languages are:")
10 for language in languages:
11 print("\t" + language.title())

Jen's favorite languages are:


Python
Ruby

Sarah's favorite languages are:


C

Edward's favorite languages are:


Ruby
Go

Phil's favorite languages are:


Python
Haskell

keyboard_arrow_down A Dictionary in a Dictionary


1 Dict = {1: 'Geeks',
2 2: 'For',
3 3: {'A' : 'Welcom', 'B' : 'To', 'C' : 'Geeks'}}
4 print("\nDictionary with the use of Mixed Keys: ")
5 print(Dict)

Dictionary with the use of Mixed Keys:


{1: 'Geeks', 2: 'For', 3: {'A': 'Welcom', 'B': 'To', 'C': 'Geeks'}}

1 # Creating a Dictionary
2 Dict = {'Dict1': {1: 'Welcome'},
3 'Dict2': {'to': 'Uop'}}
4 Dict

{'Dict1': {1: 'Welcome'}, 'Dict2': {'to': 'Uop'}}

1 # Accessing element using key


2 print(Dict['Dict1'])
3 print(Dict['Dict1'][1])
4 print(Dict['Dict2']['to'])

{1: 'Welcome'}
Welcome
Uop

A dictionary can contain dictionaries, this is called nested dictionaries .

1 myfamily = {
2 "child1" : {
3 "name" : "Emil",
4 "year" : 2004
5 },
6 "child2" : {
7 "name" : "Tobias",
8 "year" : 2007
9 },
10 "child3" : {
11 "name" : "Linus",
12 "year" : 2011
13 }
14 }
Create three dictionaries , then create one dictionary that will contain the other three dictionaries :

1 child1 = {"name" : "Emil", "year" : 2004}


2
3 child2 = {"name" : "Tobias","year" : 2007}
4
5 child3 = {"name" : "Linus","year" : 2011}
6
7 myfamily = {
8 "child1" : child1,
9 "child2" : child2,
10 "child3" : child3
11 }

1 myfamily

{'child1': {'name': 'Emil', 'year': 2004},


'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}

1 users = {'aeinstein': {'first': 'albert',


2 'last': 'einstein',
3 'location': 'Germany'},
4
5 'mcurie': {'first': 'marie',
6 'last': 'curie',
7 'location': 'paris'}}
8
9 for username, user_info in users.items():
10 print("\nUsername: " + username)
11 full_name = user_info['first'] + " " + user_info['last']
12 location = user_info['location']
13 print("\tFull name: " + full_name.title())
14 print("\tLocation: " + location.title())

Username: aeinstein
Full name: Albert Einstein
Location: Germany

Username: mcurie
Full name: Marie Curie
Location: Paris

1 users

{'aeinstein': {'first': 'albert', 'last': 'einstein', 'location': 'Germany'},


'mcurie': {'first': 'marie', 'last': 'curie', 'location': 'paris'}}

1 for username, user_info in users.items():


2 print("\nUsername: " + username)
3 for k,v in user_info.items():
4 print(k,v)

Username: aeinstein
first albert
last einstein
location Germany

Username: mcurie
first marie
last curie
location paris
If the key does not exist , insert the key, with the specified value.

1 car = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6
7 x = car.setdefault("color", "white")
8
9 print(x)

white

1 car

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white'}

1 Dict = {}
2 print("Empty Dictionary: ")
3 print(Dict)

Empty Dictionary:
{}

1 Dict[0] = 'Hi'
2 Dict[2] = 'there'
3 Dict[3] = 1
4 print("\nDictionary after adding 3 elements: ")
5 print(Dict)
Dictionary after adding 3 elements:
{0: 'Hi', 2: 'there', 3: 1}

1 Dict['Value_set'] = 2, 3, 4
2 print("\nDictionary after adding 3 elements: ")
3 print(Dict)

Dictionary after adding 3 elements:


{0: 'Hi', 2: 'there', 3: 1, 'Value_set': (2, 3, 4)}

1 Dict[2] = 'Welcome'
2 print("\nUpdated key value: ")
3 print(Dict)

Updated key value:


{0: 'Hi', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

1 Dict[5] = {'Nested': {'1': 'nested Hi', '2': 'nested Welcome'}}


2 print("\nAdding a Nested Key: ")
3 print(Dict)

Adding a Nested Key:


{0: 'Hi', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'nested Hi', '2': 'nested Welcome'}}}

1 dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}


2
3 dict2 = dict1.copy()
4 print(dict2)

{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}

1 dict1.clear()
2 print(dict1)

{}

1 dict2[1]

'Python'

1 print(dict2.get(1))

Python

1 dict2[5]

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-82-23577deac0fd> in <cell line: 1>()
----> 1 dict2[5]

KeyError: 5

Next steps: Explain error

1 print(dict2.get(5))

None

1 print(dict2.items())

dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])

1 print(dict2.keys())

dict_keys([1, 2, 3, 4])
1 dict2.pop(4)
2 print(dict2)

{1: 'Python', 2: 'Java', 3: 'Ruby'}

1 dict2.popitem()
2 print(dict2)

output {1: 'Python', 2: 'Java'}

add Code add Text


1 dict2.update({3: "Scala"})
2 print(dict2)

{1: 'Python', 2: 'Java', 3: 'Scala'}

This material was prepared by Eng.Ghayd'a Al-Hyasat for Programming Language (2).

References:

Lutz, M. (2013). Learning python: Powerful object-oriented programming. " O'Reilly Media, Inc.".

https://datascience.com.co/

https://www.w3schools.com/python/default.asp

https://www.tutorialspoint.com/python

You might also like