473,748 Members | 6,034 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

opposite of dict.items()

Is there a method to create a dict from a list of keys and a list of
values ?

TIA
Tertius

Jul 18 '05 #1
6 2420
Tertius wrote:
Is there a method to create a dict from a list of keys and a list of
values ?

dict(zip(range( 3), "abc"))

{0: 'a', 1: 'b', 2: 'c'}

Not a method() but a method.

Peter
Jul 18 '05 #2
Peter Otten wrote:
Tertius wrote:

Is there a method to create a dict from a list of keys and a list of
values ?


dict(zip(ra nge(3), "abc"))


{0: 'a', 1: 'b', 2: 'c'}

Not a method() but a method.

Peter


much better than a for loop :)
thnx

Jul 18 '05 #3
|a = {}
|for k , v in zip(keys,values ):
| a[k] = v
keys = (1,2,3,4)
vals = 'a b c d'.split()
dct = dict(zip(keys,v als))
dct

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

--
mertz@ | The specter of free information is haunting the `Net! All the
gnosis | powers of IP- and crypto-tyranny have entered into an unholy
..cx | alliance...idea s have nothing to lose but their chains. Unite
| against "intellectu al property" and anti-privacy regimes!
-------------------------------------------------------------------------
Jul 18 '05 #4
[Tertius wrote]
Is there a method to create a dict from a list of keys and a list of
values ?
[Peter Otten]
dict(zip(range( 3), "abc")) {0: 'a', 1: 'b', 2: 'c'}

If you're using Py2.3, then the itertools way is a bit nicer:
dict(itertools. izip(range(3), "abc"))

{0: 'a', 1: 'b', 2: 'c'}
Raymond Hettinger
Jul 18 '05 #5
Tertius <tc****@ananzi. co.za> writes:
Tertius wrote:
Is there a method to create a dict from a list of keys and a list of
values ?
TIA
Tertius

I found a way...

a = {}
for k , v in zip(keys,values ):
a[k] = v


Or:
python

Python 2.3 (#1, Jul 30 2003, 21:59:29)
[GCC 3.3 (SuSE Linux)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
a=(1,2,3)
b=(4,5,6)
dict(zip(a,b)) {1: 4, 2: 5, 3: 6}


Greetings
Berthold
--
bh***@web.de / http://starship.python.net/crew/bhoel/
It is unlawful to use this email address for unsolicited ads
(USC Title 47 Sec.227). I will assess a US$500 charge for
reviewing and deleting each unsolicited ad.
Jul 18 '05 #6
On Fri, 2003-08-29 at 04:53, Peter Otten wrote:
dict(izip(irang e(3), "abc"))
{0: 'a', 1: 'b', 2: 'c'}

If I could use the above in Py2.4, it would be even nicer, namely:

- convert itertools to builtins


The push is to have LESS builtins. You can always import them in to the
current namespace:

from itertools import izip
- add irange(), perhaps as an alias for xrange() like file/open


I suggested an irange to Raymond, and even coded one up, a while ago.
He sees it as bloat, and rightfully so, since there is a push to allow
optimizations of range that would achieve the same effect. (ie. rather
than remembering when to use range(), xrange(), or irange(), we could
just always use range() and the language would do lazy evaluation
whenever possible.) Unless that avenue turns out to be a complete dead
end, don't expect an irange().

BTW. In the example you used, you COULD use xrange(). The only problem
is that range has been extended, in 2.3, to accept longs, and xrange()
only works with ints, and Guido wants it that way (he doesn't want to
extend xrange()'s features, since it is a pain.) irange(), if it ever
appears, would presumably be fully range() compatible.

--
Chad Netzer
Jul 18 '05 #7

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

Similar topics

9
12239
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after them. What I want to do is filter out a subset of this dict to produce another dict that satisfies a set of criteria (in this case whether it contains all four values) to end up with something
7
3099
by: Marcio Rosa da Silva | last post by:
Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4}
3
2050
by: Bengt Richter | last post by:
Has anyone found a way besides not deriving from dict? Shouldn't there be a way? TIA (need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-) I guess I can just document that you have to spell it dict(d.items()), but I'd like to hide the internal shenanigans ;-) Regards, Bengt Richter
15
2455
by: George Sakkis | last post by:
Although I consider dict(**kwds) as one of the few unfortunate design choices in python since it prevents the future addition of useful keyword arguments (e.g a default value or an orderby function), I've been finding myself lately using it sometimes instead of dict literals, for no particular reason. Is there any coding style consensus on when should dict literals be preferred over dict(**kwds) and vice versa ? George
15
6628
by: Jay Tee | last post by:
Hi, I have some code that does, essentially, the following: - gather information on tens of thousands of items (in this case, jobs running on a compute cluster) - store the information as a list (one per job) of Job items (essentially wrapped dictionaries mapping attribute names to values)
20
2423
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001: ,
3
1425
by: Phoe6 | last post by:
I have a requirement for using caseless dict. I searched the web for many different implementations and found one snippet which was implemented in minimal and useful way. ############# import UserDict class CaseInsensitiveDict(dict, UserDict.DictMixin): def __init__(self, *args, **kwargs): self.orig = {}
10
1675
by: Gerard flanagan | last post by:
Simon Mullis wrote: data = from itertools import groupby datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: s)) print datadict
6
2730
by: Ernst-Ludwig Brust | last post by:
Given 2 Number-Lists say l0 and l1, count the various positiv differences between the 2 lists the following part works: dif= da={} for d in dif: da=da.get(d,0)+1 i wonder, if there is a way, to avoid the list dif
0
8830
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
9541
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...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9321
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
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3312
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
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.