Dictionaries

Dictionary is a list of index-value items.

Creating dict

Creating dict with literals

Simple Dictionary

In [53]:

animal_counts = { 'cats' : 2, 'dogs' : 5, 'horses':4}
print (animal_counts)
{'cats': 2, 'dogs': 5, 'horses': 4}

Dictionary with list

In [54]:

animal_names = {'cats':   ['Walter','Ra'],
                'dogs':   ['Jim','Roy','John','Lucky','Row'],
                'horses': ['Sax','Jack','Ann','Jeep']
               }
print (animal_names)
{'cats': ['Walter', 'Ra'], 'dogs': ['Jim', 'Roy', 'John', 'Lucky', 'Row'], 'horses': ['Sax', 'Jack', 'Ann', 'Jeep']}

Creating dict with variables

In [55]:

#cat_names : ['Walter','Ra','Jim']
#dog_names  : ['Jim','Roy','John','Lucky','Row']
#horse_names: ['Sax','Jack','Ann','Jeep']
#animal_names = {'cats': cat_names,'dogs': dog_names, 'horses': horse_names}
#animal_names

Accessing dict

Find out the list of keys using keys()

In [56]:

print (animal_counts.keys())
print (sorted(animal_counts.keys()))
dict_keys(['cats', 'dogs', 'horses'])
['cats', 'dogs', 'horses']

Find out the list of values using values()

In [57]:

print (animal_counts.values())
print (sorted(animal_counts.values()))
dict_values([2, 5, 4])
[2, 4, 5]

Refer a dictionary item using index

In [58]:

animal_counts['dogs']

Out[58]:

5

Accessing non-existance key natively will return Error

In [59]:

##animal_count['cow']

Accessing non-existance key with get() will return None

In [60]:

print (animal_counts.get('cow'))
None

results matching ""

    No results matching ""