Python dictionaries and lists

dictionaries_vs_lists

Dictionaries and lists are one of the most important and very powerful data structure to master in python. Today, i want to share a trick to help anyone doing python to be able to play around with them.

If you have two lists, you can make a dictionary from the lists, one being the keys, the other being the value. Let me demonstrate this:

names = [‘Lorna’, ‘Eunice’, ‘Gillian’, ‘Lynn’] #initialize list called names                        address = [‘Kikoni’, ‘MaryStuart’, ‘Aka’, ‘Muhika’] #initialize a list for addresses
names_to_address = dict(list(zip(names, address)))
print names_to_address

Result:
{‘Lorna’: ‘Kikoni’, ‘Eunice’: ‘MaryStuart’, ‘Gillian’: ‘Aka’, ‘Lynn’: ‘Muhika’}

Awesome right!!

Good luck as you practice!

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 )

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