Evan Bloemer
Evan Bloemer

Reputation: 1081

Python add to a list that is a value of a key

I am trying to add to a list that is a value of a key in two different (operations?). Below is an example:

item['foo'] = ["blah"]
item['foo'] = ["garble"]

where item is a dictionary and foo is a key. Then if I print foo I get:

["garble"]

when I want

["blah", "garble"]

How do I get the end result I want?

EDIT: formating

Upvotes: 2

Views: 1524

Answers (8)

Saksham Varma
Saksham Varma

Reputation: 2130

You can use setdefault. It would try to look for 'foo' at first; if it cannot find it, setdefault would add 'foo' to item dictionary, with corresponding value as [], and would also return the reference to this value. To this returned value, you can append entries from vals list.

If setdefault is able to find the key 'foo' in the dictionary, it simply returns the corresponding value for it, which would again be a list.

item = {}
vals = ['blah', 'garble']

for x in vals:
    item.setdefault('foo', []).append(x)
print item['foo']         # print ['blah', 'garble']

Upvotes: 1

Close you just need to append it

item = dict()

item['foo'] = ["blah"]
#above sets key foo to list value blah
#either of below appends a new value to the foo's list
item['foo'] += ["garble"] 
#or item['foo'].append("garble")
#note if this method is used list notation is needed to stop interpretation
# of each character. So I'd use append but wanted to show how close you were

print item
#outputs: {'foo': ['blah', 'garble']}

@PythonNoob see the comment if += works for you it works but .append would be the preferred method and I'd also look at @Zizouz212 answer as the extend feature is a useful addition.

Upvotes: 1

clj
clj

Reputation: 303

What you are doing with the code shown is first assigning the value ['blah'] to the key 'foo', and then, in the next step, assigning the value ['garble'] to the key 'foo'. A key can only be assigned to one value (and by "value", we mean any type, be it an integer, a string, a list, a tuple, etc.), so the second assignment overwrites the first. What you want is for the key 'foo' be assigned to the list ["blah", "garble"]. The list is one value. This can be done in one step like this:

item['foo'] = ["blah", "garble"]

or, if, for some reason, you want to create a key value pair where the value is a list, and then add an item to that list later, this is how you would do it:

item['foo'] = ['blah']
item['foo'].append('garble')

The first line assigns the list ['blah'] to the key 'foo'. The second line retrieves the value assigned to the key 'foo' from the dictionary item, applies the list method .append() to it (which will ONLY work if the value retrieved from the dictionary with the key 'foo' IS in fact a list!), and then appends to that list the string 'garble'. The result is:

>>> item['foo']
['blah', 'garble']

Do NOT do this:

item['foo'].append(['garble'])

or you will end up with the second element of this list another list, like this:

['blah', ['garble']]

Upvotes: 2

Shashank
Shashank

Reputation: 13869

I would use collections.defaultdict in combination with list.extend:

>>> from collections import defaultdict
>>> dd = defaultdict(list)
>>> dd[1].extend([2]) # You can now do stuff like this without initialization
>>> dd[1].extend((3, 4)) # No worries, hakuna matata style
>>> dd[1]
[2, 3, 4]

In my opinion, this makes the code very simple and clean.

You can also use list.append to add a single element to the list instead of all the elements of an iterable:

>>> dd[1].append(5)
>>> dd[1]
[2, 3, 4, 5]

Upvotes: 1

Zizouz212
Zizouz212

Reputation: 4998

To get the values of the key:

>>> item["foo"] = ["bar"] # bar is the value

If bar is a list, you can use all of the methods that are already associated with it. Here we use append.

>>> item["foo"].append("meh")
>>> item["foo"]
["bar", "meh"]

Of course, if you want to add a list (and have it be "merged"), you the extend method.

>>> item["foo"].extend(["gar", "ble"])
>>> item["foo"]
["bar", "meh", "gar", "ble"]

If you don't use extend there, you'll have a nested list:

["bar", "meh", ["gar", "ble"]]

Upvotes: 1

koukouviou
koukouviou

Reputation: 820

Since you want the value to be a list, you should append to item['foo'] like this:

item = {}
item['foo'] = ["blah"]
item['foo'].append("garble")
print(item)

which prints out:

{'foo': ['blah', 'garble']}

If garble is a list, for example something like garble = ["blah2"], you can do list merging like this:

item = {}
item['foo'] = ["blah"]
garble = ["blah2"]
item['foo'] += garble
print item

Which in turn prints out:

{'foo': ['blah', 'blah2']}

Upvotes: 6

Carson Crane
Carson Crane

Reputation: 1217

>>> item = {}
>>> item['foo'] = ["blah"]
>>> item['foo'].append("garble")
>>> item
{'foo': ['blah', 'garble']}
>>>

Upvotes: 0

101
101

Reputation: 8999

You are overwriting the dictionary value instead of appending to it, try:

item['foo'] = ['blah']
item['foo'].append('garble')

Upvotes: 2

Related Questions