Dictionary
Dictionary
Dictionary
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)
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)
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)
1 #Dictionary Length
2 print("Number of elements in dict:",len(dict1))
1 dict1
1 # Get items
2 print("Items are ", dict1.items())
1 # Get Keys
2 print("Keys are ", dict1.keys())
1 # Get values
2 print("Values are ", dict1.values())
'beauty'
1 dict1.get('b')
'beauty'
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
{'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"])
{'key1': 'value1', 'key2': 'value2', 'key0': 'value0', 'key3': 'value3', 'key4': 'value4'}
1 mydict.pop("key2")
2 print(mydict)
1 mydict.popitem()
2 print(mydict)
1 mydict.popitem()
2 print(mydict)
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
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
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)
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")
1 dict1 = {
2 'b': 'beauty',
3 'j': 'joy',
4 'c': 'computing'
5 }
6
7 dict1.update({"b": "Hi"})
8 dict1
1 dict1.update({'p': "Python"})
2 dict1
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)
1 thisdict
1 mydict1 = dict(thisdict)
2 print(mydict1)
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
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()
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
Sarah
Edward
Phil
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())
1 # Creating a Dictionary
2 Dict = {'Dict1': {1: 'Welcome'},
3 'Dict2': {'to': 'Uop'}}
4 Dict
{1: 'Welcome'}
Welcome
Uop
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 myfamily
Username: aeinstein
Full name: Albert Einstein
Location: Germany
Username: mcurie
Full name: Marie Curie
Location: Paris
1 users
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
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)
1 Dict[2] = 'Welcome'
2 print("\nUpdated key value: ")
3 print(Dict)
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
1 print(dict2.get(5))
None
1 print(dict2.items())
1 print(dict2.keys())
dict_keys([1, 2, 3, 4])
1 dict2.pop(4)
2 print(dict2)
1 dict2.popitem()
2 print(dict2)
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