Dictionaries
- Collection of unordered data.
Key-Value
pairs
- You access the value by refering the key.
d = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
d["key1"] # Call
d["key1"] = "value12" # Set
d.items()
d.keys()
d.values()
len(d) d.len()
d.update( { “key4” : “value4” } )
d2 = {}
# Empty Dictionary
d2["key2_1"] = "value2_1"
d.union(d2)
print(d)
print(d["key2_1"])
del d["key1"]
d.pop("key1")
d.clear()
Loops
for k in d:
print("%s : %s" %( k , d[k ]))
for k, val in d.items():
print("%s : %s" %( k , val ))
for k in d.keys():
print("%s : %s" %( k , val ))
print(k, “\t”, d[k])
for value in d.values():
print(value)
player = {
"Name": "N00b_Master",
"Character": "Malzahar",
"Level": 25
}
len( player) # 3
player[“Name”] # "N00b_Master"
player[“Weapon”]= “Axe”
player[“Level] =+ 1
if “weapon” in player:
del “weapon” # Delete
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781 }
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
del phonebook["John"]
if "John" not in phonebook:
phonebook["John"] = 938478998
Compare Dictionaries
for k in d1.keys():
if k in d2:
...
cmp(d1,d2) # 0 if equal
Indexation List
colours = { 1:"red",2:"blue",3:green}
colours[2] = "yellow"
Dictionary Merge
# How to merge two dictionaries
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
# z
# {'c': 4, 'a': 1, 'b': 3}
# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}
# How to sort a Python dict by value
# (== get a representation sorted by value)
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or:
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# How to merge two dictionaries
# in Python 3.5+
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}
>>> z = {**x, **y}
>>> z
{'c': 4, 'a': 1, 'b': 3}
# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}
# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting
# duplicates from left to right.
# The get() method on dicts
# and its "default" argument
name_for_userid = {
382: "Alice",
590: "Bob",
951: "Dilbert",
}
def greeting(userid):
return "Hi %s!" % name_for_userid.get(userid, "there")
>>> greeting(382)
"Hi Alice!"
>>> greeting(333333)
"Hi there!"
food = { “Kiwi”:1, “Apple”:5}
print(“Strawberry” in food.keys())
food.update({ “Kiwi”:1, “Apple”:3}
foos.pop(“Kiwi”)
Dictionary methods
Get value
person = { "name" : 'John'}
print( person.get("name")) # returns the name
print( person.get("age", "Age unknown.")
# provides alternative value. SAFE