Dictionaries

– Find all keys in a dict with the same value

match = 1
d = {'a':1, 'b':2, 'c':3, 'd':1}
for k,v in [(k,v) for k,v in d.iteritems() if v == match]:
  print k
-----------------------------------------------------------------------
a
b

– Count the number of items in a list and covert to dictionary

import collections
l = [1,2,2,3,4,5,5,5,6]
c = collections.Counter(l)
for k,v in c.iteritems():
    print '{} occurs {} time(s)'.format(k,v)
-----------------------------------------------------------------------
1 occurs 1 time(s)
2 occurs 2 time(s)
3 occurs 1 time(s)
4 occurs 1 time(s)
5 occurs 3 time(s)
6 occurs 1 time(s)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s