473,395 Members | 1,464 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,395 software developers and data experts.

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.strftime('%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 28270
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.strftime('%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.__setitem__(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.strftime('%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.strftime('%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.strftime('%m')),d.id) for d in links] )

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

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

May 27 '07 #4
In <11*********************@o11g2000prd.googlegroups. com>, half.italian
wrote:
[entries.__setitem__(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
comprehension.
....
>
entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] )

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

entries = dict( (int(d.date.strftime('%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.orgescrib ió:
>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
On May 28, 12:25 am, Marc 'BlackJack' Rintsch <bj_...@gmx.netwrote:
In <1180299814.129770.93...@o11g2000prd.googlegroups. com>, half.italian
wrote:
[entries.__setitem__(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
It's ugly I agree, but it was the first solution I found. I need you
guys for the _right_ solutions :) I have stumbled over the same
situation myself. I don't see that the list comprehension itself is
misleading. If nothing is catching the empty list that is returned,
it signals that the returned list is unimportant, and if wrapped by a
call to dict() its obvious also.

Do you think we just shouldn't use list comprehensions to build
dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?

~Sean

May 28 '07 #11
ha**********@gmail.com wrote:
Do you think we just shouldn't use list comprehensions to build
dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?
Use list comprehensions where you need the resulting list; if you want
nothing but the side effects, use a for loop.

[Stefan Sonnenberg-Carstens]
a = [1,2,3,4,5,6,7,8,9,10]
aDict = dict([(x,x+1) for x in a if x%2==0])
Stefan's example meets the above criterion, so yes, it's acceptable. In
Python 2.5 you would use a generator expression, though:

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

Peter

May 28 '07 #12
En Mon, 28 May 2007 05:37:12 -0300, Wim Vogelaar
<wi**************************@bag.python.orgescrib ió:
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
Keys in a dictionary are listed in an arbitrary order; the *only* thing
about the ordering you can say is that, given a FIXED dictionary (already
constructed, and without any other intervening operation that could alter
its content), when you iterate over its keys (using .keys(), .iterkeys()),
its values (.values(), .itervalues()) or items (.items(), .iteritems())
you will always get the same things in the same order over and over.
If you create the dictionary using a different sequence of insertions and
deletions, you may get different results. If you insert and delete things
afterwards, you may get different results. If you exit the program and run
it again, you may get different results. The *only* guaranteed fact is
that you will get the same results provided you don't modify the
dictionary at all.

See note (3) in http://docs.python.org/lib/typesmapping.html

--
Gabriel Genellina

May 28 '07 #13
"Wim Vogelaar" <wim.vogelaar at mc2world dot orgwrote:
>
>>
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}
.... and it will become unordered again when you get up to storing 32 in the
dictionary, and ordered again when you get up to 44.

It is an unfortunate side-effect of the way that Python dictionaries work
that it often appears when you store small integers as though they are
being stored sorted. In fact the order depends on the order in which you
inserted the values into the dictionary, the current size allocated to the
dictionary, and whether any slots have previously been occupied by other
values.

In your original output:

{8: 9, 2: 3, 4: 5, 10: 11, 6: 7}

the keys 2, 4, and 6 are inserted into the 2nd, 4th, 6th slots of the
dictionary (counting from 0 and there are initially 8 slots), 8 goes into
the 0th slot, 10 would go into the 2nd slot except that is filled so it
ends up in the 5th slot.

When you insert 12, the initial dictionary is too full (it never fills all
the slots), so it is resized to have 32 slots. Again the 32 wraps round to
the 0th slot and higher values all collide with filled slots so they end up
in less obvious positions:
>>for i in range(12,42,2):
print dict.fromkeys(range(2,i,2))
{8: None, 2: None, 4: None, 10: None, 6: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None, 22: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None, 22: None, 24: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None, 22: None, 24: None, 26: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16:
None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14:
None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None,
30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34:
None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None,
28: None, 30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34:
None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 36: None,
26: None, 28: None, 30: None}
{32: None, 2: None, 4: None, 38: None, 6: None, 8: None, 10: None, 12:
None, 34: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None,
36: None, 26: None, 28: None, 30: None}

The fact that integers hash to themselves may be unlikely to change, but
the sizes of the hash tables, or the conflict resolution strategy when an
insertion hits an already used slot could all vary in other versions of
Python.
May 28 '07 #14
Tim Churches <tc***@optushome.com.auwrites:
http://shaheeilyas.com/flags/

Scroll to the bottom to see why this is not entirely off-topic.
I fail to see what it has to do with the thread you're replyiing to,
which is a discussion of creating a dictionary from a list
comprehension.

If you want to start a new thread, compose a new message, not a reply
to an existing thread.

--
\ "If you ever catch on fire, try to avoid seeing yourself in the |
`\ mirror, because I bet that's what REALLY throws you into a |
_o__) panic." -- Jack Handey |
Ben Finney
May 28 '07 #15

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

Similar topics

14
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
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...
7
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...
3
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...
24
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...
18
by: a | last post by:
can someone tell me how to use them thanks
14
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...
11
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...
10
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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...

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.