473,383 Members | 1,803 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Create dict from two lists

py
I have two lists which I want to use to create a dictionary. List x
would be the keys, and list y is the values.

x = [1,2,3,4,5]
y = ['a','b','c','d','e']

Any suggestions? looking for an efficent simple way to do this...maybe
i am just having a brain fart...i feel like this is quit simple.

thanks.

Feb 10 '06 #1
9 24658
py wrote:
I have two lists which I want to use to create a dictionary. List x
would be the keys, and list y is the values.

x = [1,2,3,4,5]
y = ['a','b','c','d','e']

Any suggestions? looking for an efficent simple way to do this...maybe
i am just having a brain fart...i feel like this is quit simple.


dict(zip(x,y))

Diez
Feb 10 '06 #2
"py" <co*******@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
I have two lists which I want to use to create a dictionary. List x
would be the keys, and list y is the values.

x = [1,2,3,4,5]
y = ['a','b','c','d','e']

Any suggestions? looking for an efficent simple way to do this...maybe
i am just having a brain fart...i feel like this is quit simple.

thanks.


x = [1,2,3,4,5]
y = ['a','b','c','d','e']
dict(zip(x,y))

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

-- Paul
Feb 10 '06 #3
On Fri, 2006-02-10 at 08:51, py wrote:
I have two lists which I want to use to create a dictionary. List x
would be the keys, and list y is the values.

x = [1,2,3,4,5]
y = ['a','b','c','d','e']

Any suggestions? looking for an efficent simple way to do this...maybe
i am just having a brain fart...i feel like this is quit simple.


d = dict(zip(x,y))

-Carsten
Feb 10 '06 #4
Diez B. Roggisch wrote:
py wrote:
I have two lists which I want to use to create a dictionary. List x
would be the keys, and list y is the values.

x = [1,2,3,4,5]
y = ['a','b','c','d','e']

Any suggestions? looking for an efficent simple way to do this...maybe
i am just having a brain fart...i feel like this is quit simple.


dict(zip(x,y))

Diez

I'd even suggest using izip (from itertools), it's often much faster
than zip (end result is the same).

Demo:
from itertools import izip
l1 = range(5000)
l2 = range(5000, 10000)
from timeit import Timer
t1 = Timer("dict(zip(l1, l2))", "from __main__ import l1, l2")
t2 = Timer("dict(izip(l1, l2))", "from __main__ import l1, l2, izip")
min(t1.repeat(5, 10000)) 17.989041903370406 min(t2.repeat(5, 10000)) 10.381146486494799


42% speed gain from using izip instead of zip (memory was not an issue
during the test, machine had 1.3Gb of available ram)
Feb 10 '06 #5
py
Thanks, itertools.izip and just zip work great. However, I should have
mentioned this, is that I need to keep the new dictionary sorted.

d = {1:'first', -5 : 'negative 5', 6:'six', 99:'ninety-nine',
3:'three'}
keys = d.keys()
keys.sort()
vals = map(d.get, keys)

At this point keys is sorted [-5, 1, 3, 6, 99] and vals is sorted
['negative 5', 'first', 'three', 'six', 'ninety-nine']

Using zip does not create the dictionary sorted in this order.
new_d = dict(zip(keys, vals))

How can I use the two lists, keys and vals to create a dictionary such
that the items keep their order?

Thanks.

Feb 10 '06 #6

py wrote:
Thanks, itertools.izip and just zip work great. However, I should have
mentioned this, is that I need to keep the new dictionary sorted.

d = {1:'first', -5 : 'negative 5', 6:'six', 99:'ninety-nine',
3:'three'}
keys = d.keys()
keys.sort()
vals = map(d.get, keys)

At this point keys is sorted [-5, 1, 3, 6, 99] and vals is sorted
['negative 5', 'first', 'three', 'six', 'ninety-nine']

Using zip does not create the dictionary sorted in this order.
new_d = dict(zip(keys, vals))

How can I use the two lists, keys and vals to create a dictionary such
that the items keep their order?

Thanks.


Short answer - you can't. Dictionaries aren't sequential structures,
so they have no sorted form. You can iterate through it in a sorted
manner however, as long as you keep your list of keys:

keys.sort()
for k in keys:
print d[k]

Iain

Feb 10 '06 #7
py wrote:
Thanks, itertools.izip and just zip work great. However, I should have
mentioned this, is that I need to keep the new dictionary sorted.


Dictionaries aren't sorted. Period.

/MiO
Feb 10 '06 #8
py:
Thanks, itertools.izip and just zip work great. However, I should have
mentioned this, is that I need to keep the new dictionary sorted.


A Python dictionary is an unsorted data structure, so you cannot have
it sorted as you please.
(I have seen that lot of people ask for a sorted dictionary and for
permutation/combination functions, maybe they are batteries to be
included too in the standard library.)
If you need an ordered dict you can manage it yourself, keeping the
lists of keys, etc, or you can use an ordered dict implementation:

http://www.voidspace.org.uk/python/odict.html
http://aspn.activestate.com/ASPN/Coo.../Recipe/438823
Etc.

Bye,
bearophile

Feb 10 '06 #9
py
Iain King wrote:
Short answer - you can't. Dictionaries aren't sequential structures,
so they have no sorted form. You can iterate through it in a sorted
manner however, as long as you keep your list of keys:

keys.sort()
for k in keys:
print d[k]

Iain


duh!....thanks.

Feb 10 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Wolfgang.Stoecher | last post by:
Hello, I'm new to Python and playing around. I'm confused by the following behaviour: >>> l1 = # define list >>> l2 = l1 # copy of l1 ? >>> l2,l1 (, ) >>> l2.extend(l1) # only l2 should...
4
by: Lorn | last post by:
I'm trying to figure out a way to create dynamic lists or possibly antother solution for the following problem. I have multiple lines in a text file (every line is the same format) that are...
7
by: Chris Stout | last post by:
I'm a system developer and won't even pretend that I'm a designer, but I want to move our graphics designers off of "old way" of hacking html to get desired results, to marking up documents...
11
by: sandravandale | last post by:
I can think of several messy ways of making a dict that sets a flag if it's been altered, but I have a hunch that experienced python programmers would probably have an easier (well maybe more...
37
by: Steven Bethard | last post by:
The PEP below should be mostly self explanatory. I'll try to keep the most updated versions available at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt...
18
by: Steven Bethard | last post by:
I've updated the PEP based on a number of comments on comp.lang.python. The most updated versions are still at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt...
0
by: Steve1974 | last post by:
Hi All I am currently using Access to output to excel. The creation of the worksheet goes ok, and then I have a piece of code (recorded from an Excel macro) to create pick lists for two columns...
24
by: Dan2kx | last post by:
Hello to all that read and thank you to all that post Background: I have been tasked to create a holiday database for the employees in my lab, (so expect many more posts) im stuck at the first...
3
by: bruce | last post by:
hi guys/gals... got a basic question that i can't get my hands around. i'm trying to programatically create/use a list/tuple (or whatever the right phrase in pyton is!!) basically,...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.