473,656 Members | 2,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 24673
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*******@gmai l.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.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(izi p(l1, l2))", "from __main__ import l1, l2, izip")
min(t1.repeat(5 , 10000)) 17.989041903370 406 min(t2.repeat(5 , 10000)) 10.381146486494 799


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
1465
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 be altered !?
4
2313
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 iterated over and which need to be compared to previous lines in the file in order to perform some simple math. Each line contains 3 fileds: a descriptor and two integers. Here is an example: rose, 1, 500 lilac, 1, 300 lilly, 1, 400
7
3633
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 according to current web standards. I've been trying to design on of our new pages myself, but the biggest problem I'm running into is trying to create multicolumn lists. I have a list of items, which is most definitely a list, not a table, but I...
11
2071
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 Pythonic) way of doing this. It's important that I can read the contents of the dict without flagging it as modified, but I want it to set the flag the moment I add a new element or alter an existing one (the values in the dict are mutable), this...
37
3284
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 http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html PEP: XXX Title: The create statement
18
2708
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 http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html In this post, I'm especially soliciting review of Carl Banks's point (now discussed under Open Issues) which asks if it would be better to have the create statement translated into:
0
1609
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 in my newly created excel file. This is supposed to run on a loop to create multiple spreadsheets, however, after successfully creating the first sheet I get an error and the process fals over. This is the error I get from the debugger: RTE...
24
2877
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 hurdle, i want to have a table with emplyee details, and to create a new table for each employee to include holiday dates and ammounts etc, so i need a create table query to creat a brand new (unrelated query) for each employee. in the "staff"...
3
1742
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, something like: foo = foo.append('cat')
0
8380
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8296
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8497
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8598
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2721
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1598
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.