By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,285 Members | 1,691 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,285 IT Pros & Developers. It's quick & easy.

How to create a dictionary using 2 lists?

P: n/a
I've 2 lists say:
Expand|Select|Wrap|Line Numbers
  1. list1 = ['a','b','c']
  2. list2 = [1,2,3]
and i want a dictionary as an output:
Expand|Select|Wrap|Line Numbers
  1. dict1 = {'a':1,'b':2,'c':3}
How to achieve this using Built in Functions?
Oct 7 '10 #1
Share this Question
Share on Google+
4 Replies

Expert Mod 5K+
P: 9,731
Why not just loop through each list and set the dictionary values?

For example:
(pseudo code)
Expand|Select|Wrap|Line Numbers
  1. Loop through List1 and List2
  2.   For this iteration get the Key from List1
  3.   For this iteration get the Value from List2
  4.   Add an item to the dictionary at the Key with the Value for this iteration
  5. Increment the iteration and go back to the start of the loop
Oct 7 '10 #2

P: n/a
Thanks mate for your reply..

i was looking for some built in function.. i faced an interview today and i was clueless when they asked me to use built in functions of python..
Oct 7 '10 #3

Expert Mod 2.5K+
P: 2,851
Expand|Select|Wrap|Line Numbers
  1. >>> dict(zip(['a','b','c'], [1,2,3]))
  2. {'a': 1, 'c': 3, 'b': 2}
  3. >>> 
Oct 7 '10 #4

P: n/a
Thanks mate..
That works :)
Oct 7 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.