Martin
Martin

Reputation: 130

Appending values to all keys of python dictionary

I have the following dictionary:

dic={'a': {'aa': [], 'ab': [], 'ac': []}, 'b': {'ba': [], 'bb': [], 'bc': []}}

I want to append three values to either all keys in 'a' or 'b'. Following example works:

dic['a']['aa'].append(value_a)
dic['a']['ab'].append(value_b)
dic['a']['ac'].append(value_c)

Any way where I can do this in one single line. What I'm searching for is something like the following:

dic['a'][*] = [value_a, value_b, value_c]

Where * is a wildcard indexing all keys in dic['a'].

As the complexity of the dictionary in my actual program grows my current working example becomes unreadable. So my motivation for this is mainly readability.

Upvotes: 2

Views: 6983

Answers (2)

JohanL
JohanL

Reputation: 6891

To use a true one-liner (i.e., not writing a forloop in one line) it is possible to use map and exploit the mutability of dicts:

dic={'a': {'aa': [], 'ab': [], 'ac': []}, 'b': {'ba': [], 'bb': [], 'bc': []}}
vals = [1,2,3]
key = 'a'

map(lambda kv: dic[key][kv[0]].append(kv[1]), zip(dic[key], vals))

This will return [None, None, None] but the dict will be updated. However, I would suggest that it would be better to use an explicit for loop, as a two-liner:

for k, v in zip(dic[key], vals):
    dic[key][k].append(v)

Note that this will add a separate value to each of the entries in the dict, as this is what I interpret to be what is wanted.

Upvotes: 1

Miket25
Miket25

Reputation: 1903

If a loop is acceptable for your single-line solution, then this may be used.

for key in dic['a']: dic['a'][key].append(value)

If you have a list of values, you can extend the list.

for key in dic['a']: dic['a'][key].extend([value_a, value_b, value_c])

Upvotes: 3

Related Questions