Python Dictionary

Creating a dictionary

>>> my_dict[‘key1′]=’value1’
>>> my_dict[‘key2′]=’value2’
>>> my_dict[‘key3′]=’value3’
>>> my_dict
{‘key3’: ‘value3’, ‘key2’: ‘value2’, ‘key1’: ‘value1’}

or

>>> my_dict = {‘A’:0, ‘B’:1, ‘C’:2, ‘D’:3, ‘E’:4}

Iterating through python dictionary

>>> my_dict = {‘A’:0, ‘B’:1, ‘C’:2, ‘D’:3, ‘E’:4}
>>> for key, value in my_dict.iteritems():
>>>  print key, value
A 0
C 2
B 1
E 4
D 3

We can also use my_dict.iterkeys() or my_dict.itervalues() to itearte of keys or values in the dictionary

 

Advertisements

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