Definition: awesome, but kind of annoying.
>>> mydict = {}
>>>
>>> mydict['key1'] = 'my first value'
>>> mydict['key2'] = 'my second value'
>>>
>>> mydict
{'key2': 'my second value', 'key1': 'my first value'}
Remember that it needs to exist to be mutated.
use the
dict[key] = value
to add values to your dictionary
>>> mydict
{'key2': 'my second value', 'key1': 'my first value'}
>>> mydict['key1']
'my first value'
>>> mydict['key2']
'my second value'
Call a value from your dictionary with the
dict[key]
formula
Returns a list of all the keys.
>>> mydict
{'key2': 'my second value', 'key1': 'my first value'}
>>> mydict['key1']
'my first value'
>>> mydict['key2']
'my second value'
>>> mydict['key2'] = 'this is another value'
>>> mydict['key2']
'this is another value'
Use the same assignment syntax.
There are many ways.
They all are super annoying.
>>> for something in mydict:
... print something
...
key2
key1
wat.
Where are the values?
Bookmark this:
https://docs.python.org/2/library/stdtypes.html#dict
>>> countedlist
{'blue': 11, 'green': 10, 'red': 9}
>>> for key, value in countedlist.iteritems():
... print key, value
...
blue 11
green 10
red 9
>>> players = {1:{'name':'foo'},
2:{'name': 'fizzy'},
3: {'name': 'pop'}}
>>> for key, value in players.iteritems():
... innerdictkeys = value.keys()
... print key,
... for item in innerdictkeys:
... print value[item]
That's normal.
The only thing that makes it better is practice.
>>> from collections import Counter
>>> import random
>>> letters = ['a','b','c']
>>> mylist = [random.choice(letters) for i in range(50)]
>>> mylist
['b', 'a', 'b', 'c', 'c', 'a', 'b', 'b', 'c', 'b',
'b', 'a', 'c', 'c', 'c', 'a', 'a', 'b', 'a', 'b',
'b', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a',
'c', 'b', 'a', 'a', 'a', 'b', 'a', 'c', 'c', 'a',
'b', 'a', 'c', 'a', 'c', 'b', 'a', 'b', 'c', 'c']
>>> countedlist = Counter(mylist)
>>> countedlist
Counter({'a': 17, 'b': 17, 'c': 16})
That's awesome. How do we do this by hand?
>>> colors = ['red','green','blue']
>>> mylist = [random.choice(colors) for i in range(30)]
>>> countedlist = {}
>>> mylist
['red', 'green', 'green', 'green', 'red', 'blue',
'green', 'red', 'blue', 'blue', 'green', 'red',
'red', 'blue', 'blue', 'blue', 'green', 'green',
'blue', 'blue', 'blue', 'red', 'red', 'red',
'green', 'green', 'blue', 'red', 'green', 'blue']
>>> for candy in mylist:
... if candy in countedlist:
... countedlist[candy] += 1
... else:
... countedlist[candy] = 1
...
>>> countedlist
{'blue': 11, 'green': 10, 'red': 9}