lost and found ( for me ? )

Showing posts with label dictionary. Show all posts
Showing posts with label dictionary. Show all posts

how to append dictionary into dictionary

small tips

>>> a = {}
>>> b = {'a':3}
>>> c = {'b':4}

>>> b
{'a': 3}
>>> c
{'b': 4}

>>> a.update(b)
>>> a.update(c)
>>> a
{'a': 3, 'b': 4}

python : sort dictionary by values

Reference
http://stackoverflow.com/questions/1915564/python-convert-a-dictionary-to-a-sorted-list-by-value-instead-of-key

Small tips.
Here is how to sort dictionary by values

sample script
# cat sort_dict_by_value.py
#!/usr/bin/env python

from operator import itemgetter

dict = {"a":860, "b":12, "c":1200, "d":100, "e":1}

for i in sorted(dict.items(), key=itemgetter(1), reverse=True):
   print i

output
# ./sort_dict_by_value.py
('c', 1200)
('a', 860)
('d', 100)
('b', 12)
('e', 1)

itemgetter()
>>> from operator import itemgetter
>>> itemgetter(1)('abcdefg')
'b'
>>> itemgetter(1,5)('abcdefg')
('b', 'f')