473,651 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can python create a dictionary from a list comprehension?

Hi,

I'm trying to turn o list of objects into a dictionary using a list
comprehension.

Something like

entries = {}
[entries[int(d.date.strf time('%m'))] = d.id] for d in links]

I keep getting errors when I try to do it. Is it possible? Do
dictionary objects have a method equivalent to [].append? Maybe a
lambda?

Thanks for your help!
Erik

May 27 '07 #1
14 28290
On May 27, 1:55 pm, erikcw <erikwickst...@ gmail.comwrote:
Hi,

I'm trying to turn o list of objects into a dictionary using a list
comprehension.

Something like

entries = {}
[entries[int(d.date.strf time('%m'))] = d.id] for d in links]

I keep getting errors when I try to do it. Is it possible? Do
dictionary objects have a method equivalent to [].append? Maybe a
lambda?

Thanks for your help!
Erik
try...

[entries.__setit em__(int(d.date .strftime('%m') )], d.id) for d in
links]

btw...I was curious of this too. I used 'dir(dict)' and looked for a
method that might do what we wanted and bingo!

~Sean

May 27 '07 #2
erikcw schrieb:
Hi,

I'm trying to turn o list of objects into a dictionary using a list
comprehension.

Something like

entries = {}
[entries[int(d.date.strf time('%m'))] = d.id] for d in links]

I keep getting errors when I try to do it. Is it possible? Do
dictionary objects have a method equivalent to [].append? Maybe a
lambda?

Thanks for your help!
Erik

normally a dict(whatEver) will do ;-)

Example:

a = [1,2,3,4,5,6,7,8 ,9,10]

aDict = dict([(x,x+1) for x in a if x%2==0])

print aDict

May 27 '07 #3
On 27 mai, 22:55, erikcw <erikwickst...@ gmail.comwrote:
Hi,

I'm trying to turn o list of objects into a dictionary using a list
comprehension.

Something like

entries = {}
[entries[int(d.date.strf time('%m'))] = d.id] for d in links]

I keep getting errors when I try to do it. Is it possible? Do
dictionary objects have a method equivalent to [].append? Maybe a
lambda?

Thanks for your help!
Erik
entries = dict([ (int(d.date.str ftime('%m')),d. id) for d in links] )

With Python2.4 and above you can use a "generator expression"

entries = dict( (int(d.date.str ftime('%m')),d. id) for d in links )
Regards,
Pierre

May 27 '07 #4
In <11************ *********@o11g2 000prd.googlegr oups.com>, half.italian
wrote:
[entries.__setit em__(int(d.date .strftime('%m') )], d.id) for d in
links]

btw...I was curious of this too. I used 'dir(dict)' and looked for a
method that might do what we wanted and bingo!
This is really ugly. Except `__init__()` it's always a code smell if you
call a "magic" method directly instead of using the corresponding
syntactic sugar or built in function. And using a list comprehension just
for side effects is misleading because the reader expects a (useful) list
to be build when stumbling over a list comp and it's wasteful because an
unnecessary list of `None`\s is build and thrown away for no reason other
than to have a one liner. This is not Perl! ;-)

Ciao,
Marc 'BlackJack' Rintsch
May 28 '07 #5
Example:
>
a = [1,2,3,4,5,6,7,8 ,9,10]

aDict = dict([(x,x+1) for x in a if x%2==0])

print aDict
When I run this program I get:
{8: 9, 2: 3, 4: 5, 10: 11, 6: 7}

why this output isn't ordered, giving:
{2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }

May 28 '07 #6
Pierre Quentel a écrit :
On 27 mai, 22:55, erikcw <erikwickst...@ gmail.comwrote:
>Hi,

I'm trying to turn o list of objects into a dictionary using a list
comprehensio n.
....
>
entries = dict([ (int(d.date.str ftime('%m')),d. id) for d in links] )

With Python2.4 and above you can use a "generator expression"

entries = dict( (int(d.date.str ftime('%m')),d. id) for d in links )
You can also create dictionaries knowing only the keys the same way (ie.
a two-dimensional array) :

In [77]: dict.fromkeys(( a, b) for a in range(4) for b in range(2))
Out[78]:
{(0, 0): None,
(0, 1): None,
(1, 0): None,
(1, 1): None,
(2, 0): None,
(2, 1): None,
(3, 0): None,
(3, 1): None}
May 28 '07 #7
http://shaheeilyas.com/flags/

Scroll to the bottom to see why this is not entirely off-topic. Are
there other public examples in which Python has been used to harvest and
represent public information in useful and/or interesting ways? Ideas
for some more?

Tim C
May 28 '07 #8
>
why this output isn't ordered, giving:
{2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }

I made the original list two elements longer: a =
[1,2,3,4,5,6,7,8 ,9,10,11,12]

and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: 7, 8:
9, 10: 11, 12: 13}

I am running ActiveState ActivePython 2.5


May 28 '07 #9
En Mon, 28 May 2007 05:20:16 -0300, Wim Vogelaar
<wi************ **************@ bag.python.orge scribió:
>Example:

a = [1,2,3,4,5,6,7,8 ,9,10]

aDict = dict([(x,x+1) for x in a if x%2==0])

print aDict

When I run this program I get:
{8: 9, 2: 3, 4: 5, 10: 11, 6: 7}

why this output isn't ordered, giving:
{2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }
A dictionary is not ordered, no matter how you create it. If you want to
process the keys in order:

for key in sorted(aDict):
print key, '=', aDict[key]

(Note that sorted(aDict) returns a *list*, not a dictionary!)

--
Gabriel Genellina

May 28 '07 #10

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

Similar topics

14
15223
by: jsaul | last post by:
Hi there, wouldn't it be useful to have a 'while' conditional in addition to 'if' in list comprehensions? foo = for i in bar: if len(i) == 0: break foo.append(i)
35
2961
by: Moosebumps | last post by:
Does anyone here find the list comprehension syntax awkward? I like it because it is an expression rather than a series of statements, but it is a little harder to maintain it seems. e.g. you could do: result = for element in list: if element == 'blah':
7
2264
by: Chris P. | last post by:
Hi. I've made a program that logs onto a telnet server, enters a command, and then creates a list of useful information out of the information that is dumped to the screen as a result of the command. Here's a generic version of the code in question: ##### # Prior code opens telnet connection "tn" and logs in. tn.read_until('> ') tn.write('THE COMMAND IS HERE\n')
3
3325
by: Matt Gerrans | last post by:
This is probably so easy that I'll be embarrassed by the answer. While enhancing and refactoring some old code, I was just changing some map()s to list comprehensions, but I couldn't see any easy way to change a zip() to a list comprehension. Should I just let those sleeping dogs lie? (list comprehensions seem more readable than map(), but if the list comprehension that does the equivalent of zip() is less expressive than zip(), I'll...
24
3928
by: Mandus | last post by:
Hi there, inspired by a recent thread where the end of reduce/map/lambda in Python was discussed, I looked over some of my maps, and tried to convert them to list-comprehensions. This one I am not sure how to conver: Given three tuples of length n, b,i and d, I now do:
18
460
by: a | last post by:
can someone tell me how to use them thanks
14
1562
by: Ben | last post by:
I have recently learned how list comprehension works and am finding it extremely cool. I am worried, however, that I may be stuffing it into places that it does not belong. What's the most "pythony" way to do this: even = for x in range(0,width,2): for y in range(0,height,2): color = im.getpixel((x,y))
11
7032
by: beginner | last post by:
Hi, Does anyone know how to put an assertion in list comprehension? I have the following list comprehension, but I want to use an assertion to check the contents of rec_stdl. I ended up using another loop which essentially duplicates the functions of list comprehension. It just look like a waste of coding and computer time to me. I just wish I could put the assertions into list comprehensions.
10
15016
by: Debajit Adhikary | last post by:
I have two lists: a = b = What I'd like to do is append all of the elements of b at the end of a, so that a looks like: a =
0
8347
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
8792
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
8457
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
7294
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6157
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
4143
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...
0
4280
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
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
1
1905
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.