The most efficient way to add new keys or add old keys to a dictionary during an iteration in Python?

Here is the general situation when compiling data in dictionaries from different sources:

Say that you have a dictionary that stores lists of things, for example things that I like:

likes = {
    'colors': ['blue','red','purple'],
    'foods': ['apples', 'oranges']
}

and a second dictionary with some related meanings:

favorites = {
    'colors':'yellow',
    'desserts':'ice cream'
}

Then you want to iterate over the favorites object and either add the elements in this object to the list with the corresponding key in the love dictionary, or add a new key to it with a value that is a list containing the value in your favorites.

There are several ways to do this:

for key in favorites:
    if key in likes:
        likes[key].append(favorites[key])
    else:
        likes[key] = list(favorites[key])

or

for key in favorites:
    try:
        likes[key].append(favorites[key])
    except KeyError:
        likes[key] = list(favorites[key])

And many more ...

, , , , , . !

+3
5

collections.defaultdict, list.

>>> import collections
>>> mydict = collections.defaultdict(list)

, .append(...) , append .

defaultdict , dict likes , :

>>> mydict = collections.defaultdict(list, likes)

, list default_factory defaultdict .

+5

collection.defaultdict:

import collections

likes = collections.defaultdict(list)

for key, value in favorites.items():
    likes[key].append(value)

defaultdict , factory . list - , .

.items() , .

+3

defaultdict, dict ( ): dict.setdefault(k[, d]):

for key, val in favorites.iteritems():
    likes.setdefault(key, []).append(val)

+20 - 1989 2009 30 . , 20 , .

+2
>>> from collections import defaultdict
>>> d = defaultdict(list, likes)
>>> d
defaultdict(<class 'list'>, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']})
>>> for i, j in favorites.items():
    d[i].append(j)

>>> d
defaultdict(<class 'list'>, {'desserts': ['ice cream'], 'colors': ['blue', 'red', 'purple', 'yellow'], 'foods': ['apples', 'oranges']})
+1

defaultdict, , . defaultdict , , dict . (. defaultdict ?) . ( , ", dict.get() defaultdict" ). - , defaultdict, , , . , defaultdict - . , :

" , ". defaultdict(list) .

"I want to add this key to the list if it exists, and create a list if it does not exist." to which my_dict.get('foo', [])with append()is the answer.

What do you guys think?

+1
source

Source: https://habr.com/ru/post/1719872/


All Articles