Dictionaries in Python

✓ Dictionary – Dictionary is like list but in here indices can be any type. The association of a key and a value is called a key-value pair.

#Creating an empty dictionary
>>> abc = dict()
>>> print abc
#Adding key-value pair to dictionary
>>> abc['one'] = 'uno'
>>> print eng2sp
{'one': 'uno'}

#If key is not available in dictionary
>>> print eng2sp['four'] 
KeyError: 'four'

# Checking key in dict
>>> 'one' in eng2sp 
>>> 'uno' in eng2sp

# Checking values in dict
>>> vals = eng2sp.values()
>>> 'uno' in vals

✶ The order of items in a dictionary is unpredictable.

✓ Counting how many times each letter occured in string

def count(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
            d[c] += 1
    return d

def print_count(h):
    for c in h:
        print c, h[c]

✓ Dictionaries and Lists

#Inverting dictionary
def invert_dict(d):
    inverse = dict()
    for key in d:
       val = d[key]
       if val not in inverse:
           inverse[val] = [key]
    return inverse

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s