Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a list to a dictionary key within a for loop with an undefined key [duplicate]

Tags:

python

I'm collating some data into a dictionary, and I wonder if there is a better method to work with dictionaries

Lets assume I have a dictionary called dict_ and I initialise it as so

dict_ = {}

now I have an object that I want to iterate over and add into my dictionary.

for item in iterable:
   dict_[key_a] = item.data

this works if there is only one item.data to add to the key but what if I have an array?

I know I could do this

dict_[key_a] = []
for item in iterable:
    dict_[key_a] = [item.data]

but I wonder if there is a method where I could skip dict_[key_a] = [] to keep my code more concise?

using dict_['key_a'].append(item.data) results in a error, and rightly so.

my expected output would be

print(dict_)
{'key_a' : ['foo','bar']}

Happy Holidays to you all.

like image 385
Umar.H Avatar asked Mar 04 '23 00:03

Umar.H


1 Answers

Here's one idiomatic way, using a defaultdict for pre-initializing keys with empty lists as default values:

from collections import defaultdict
dict_ = defaultdict(list)

for item in iterable:
   dict_[key_a].append(item.data)
like image 166
Óscar López Avatar answered Mar 05 '23 15:03

Óscar López