Dictionary with Lists

S

Shaun

Hi,

I'm trying to create a dictionary with lists as the value for each
key. I was looking for the most elegant way of doing it... I thought
this would work:

testDict = {}
....
testDict [1] = testDict.get (1, []).append ("Test0") # 1 does not
exist, create empty array
print testDict
testDict [1] = testDict.get (1, []).append ("Test1")
print testDict

(Obviously I wouldn't normally write code like this.. but this is how
it would unfold in a loop)
However, the first printout gives {1: None} instead of the desired
{1: ['test']}. What's wrong with this syntax?
 
M

Mick Krippendorf

Hi,
I'm trying to create a dictionary with lists as the value for each
key. I was looking for the most elegant way of doing it...

from collections import defaultdict

d = defaultdict(list)

d["joe"].append("something")
d["joe"].append("another")
d["jim"].append("slow down, grasshopper")

print d


HTH,
mick.
 
M

Mel

Shaun said:
testDict = {}
...
testDict [1] = testDict.get (1, []).append ("Test0") # 1 does not
exist, create empty array
print testDict
testDict [1] = testDict.get (1, []).append ("Test1")
print testDict
[ ... ]
However, the first printout gives {1: None} instead of the desired
{1: ['test']}. What's wrong with this syntax?

The trouble is that the list.append method returns None, after modifying the
value of the parent list in place. So of course, None gets assigned to
testDict[1] after the valuable work has been done.

The old way to do what you want is

testDict.setdefault (1, []).append ("Test0")

The new way is to inherit from defaultdict.

Mel.
 
S

Shaun

Okay that makes sense. I was assuming that list.append returned the
new list.

thanks
 
J

John Nagle

Shaun said:
Hi,

I'm trying to create a dictionary with lists as the value for each
key. I was looking for the most elegant way of doing it...

Try using a tuple, instead of a list, for each key. Tuples
are immutable, so there's no issue about a key changing while
being used in a dictionary.

John Nagle
 
M

Mick Krippendorf

John said:
Try using a tuple, instead of a list, for each key. Tuples
are immutable, so there's no issue about a key changing while
being used in a dictionary.

Only if Shaun wanted to use lists as keys (which of course doesn't
work). Luckily he just wants them as values.

Mick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top