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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With