Dictionaries
Dictionaries
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A Story of Two Collections..
• List
OUT PUT
Retrieving Lists of Keys and Values
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
You can get a list >>> print(list(jjj))
['chuck', 'fred', 'jan']
of keys, values, or >>> print(list(jjj.keys()))
items (both) from ['chuck', 'fred', 'jan']
a dictionary >>> print(list(jjj.values()))
[1, 42, 100]
>>> print(list(jjj.items()))
[('chuck', 1), ('fred', 42), ('jan', 100)]
>>>
“tuple”
Bonus: Two Iteration Variables!
• We loop through the jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
key-value pairs in a for aaa,bbb in jjj.items() :
print(aaa, bbb)
dictionary using *two*
iteration variables aaa bbb
chuck 1
• Each iteration, the first fred 42 [chuck] 1
jan 100
variable is the key and [fred] 42
the second variable is
the corresponding [jan] 100
value for the key
Pre-Defined Methods
Dictionary Method Meaning
dict.clear() Removes all the elements of
the dictionary
dict.copy() Returns (shallow)copy of
dictionary.
dict.get(key, for key key, returns value or
default=None) default if key not in
dictionary (note that
default's default is None)
dict.items() returns a list of dict's (key,
value) tuple pairs
Contd…
Dictionary Method Meaning
dict.keys() returns list of dictionary
dict's keys
dict.setdefault key, similar to get(), but will set
default=None dict[key]=default if key is not
already in dict
dict.update(dict2) adds dictionary dict2's key-
values pairs to dict
dict.values() returns list of dictionary
dict's values
And few more…