5

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.

Umar.H
  • 22,559
  • 7
  • 39
  • 74
  • 1
    Possible duplicate of [Appending to list in Python dictionary](https://stackoverflow.com/questions/26367812/appending-to-list-in-python-dictionary) – jpp Dec 26 '19 at 01:23

2 Answers2

7

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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Here’s another possibility for funsies, using the unpack operator (edited to include switch ladder):

for item in iterable:
    if isinstance(item, str):
        dict_[key_a] = item.data
    elif isinstance(item, list):
        dict_[key_a] = [*item.data]
    ...