Dict

  • maps hashable values to arbitrary objects
  • mutable
  • More than one entry per key not allowed
  • Keys must be immutable, like strings, numbers, or tuples

Initialize a dict

In [ ]:
# Create a dict
d = {}
 
# Create a dict with initial values
d = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

Update

In [ ]:
# Change the value of a key word
d['Name'] = 'Lin'
 
# Add a new key and value
d['Major'] = 'CS'

Delete

In [ ]:
# Delete an element of the dict
del d['Name']
 
# Remove all elements of the dict
d.clear()
 
# Remove the whole dict
del d

Build-in functions

In [ ]:
# cmp, compare two dicts
dict1 = {'Name':'Lin', 'Age':37}
dict2 = {'Name':'Lin', 'Age':37}
print(dict1 == dict2) # True
 
#len, get the number of items in dict
print(len(dict1)) # 2
 
#str, convert a dict to a string
print(str(dict1)) # {'Name': 'Lin', 'Age': 37}
 
#type, check type
print(type(dict1)) # dict
 
#id, get the memory id of the dict
print(id(dict1)) #4338527904

Methods

In [ ]:
d = {}; #create a dict
 
d['Name'] = 'Lin';
d['Age'] = 38;

#has_key() has been removed in Python 3
if 'Name' in d:
    print('Has key \'Name\'')
    
#get, returns a value for the given key; if key is not available then returns default value
print(d.get('Name'))
print(d.get('Temp', 'Unknown')) # give a default value
#print(d['Temp']) # throw KeyError

#items
items = d.items();
print(type(items)) # dict_items, instead of list in Python 2
print(items)
for item in items:
    print(item) # each item is
    
#keys, return a list of keys
keys = d.keys();
print(type(keys)) # dict_keys, instead of list in Python 2
print(keys)
for key in keys:
    print(key)
    
#values, return a list of values
values = d.values();
print(type(values)) # dict_values, instead of list in Python 2
print(values)
for value in values:
    print(value)
    
#setdefault, get the value of key; if key is not available then return default value
print(d.setdefault('Age', None)) #38
print(d.setdefault('Sex', None)) #None

#update, add a dict to another dict
d2 = {'Sex': 'M', 'State': 'VA'};
d.update(d2); #{'Name':'Lin', 'Age':38, 'Sex':'M', 'State':'VA'}
print(d)

#remove and retun an arbitrary key-value pair
print(d.popitem())
In [ ]:
d = {'Name': 'Lin', 'Age': 38, 'Sex': 'M', 'State': 'VA'};
 
#iterkeys() has been removed in Python 3
#itervalues() has been removed in Python 3
#iteritems() has been removed in Python 3
i = iter(d) # equals to iter(d.keys())
for e in i:
    print(e) # Name Aage Sex State
    
#pop, remove a key and return its value, if the key does not exist, return default
t = d.pop('Name')
print(t) # Lin

k = sorted(d)
print(type(k)) # list
print(k) # ['Age', 'Sex', 'State']