How to Create Key or Append an Element to Key

How to create key or append an element to key?

Use dict.setdefault():

dict.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

How can I add new keys to a dictionary?

You create a new key/value pair on a dictionary by assigning a value to that key

d = {'key': 'value'}
print(d) # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}

If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.

Python dict how to create key or update key in one line?

Is there a way to do this using dict.setdefault() ?

Of course! There's nothing magic about setdefault; it just returns my_dict[name] if it exists, or sets my_dict[name] = default and returns default if not.

Either way, what it returns is the (potentially new) dict in my_dict[name], so all you have to do is update it:

my_dict.setdefault(name, {})[id] = pin

Or, if you really like using update instead of just [] =:

my_dict.setdefault(name, {}).update({id: pin})

For example:

>>> my_dict.setdefault('name1', {})['id10']= 'pin10'
>>> my_dict.setdefault('name3', {})['id20']= 'pin20'
{'name1': {'id1': 'pin1', 'id10': 'pin10', 'id2': 'pin2'},
'name2': {'id3': 'pin3', 'id4': 'pin4'},
'name3': {'id20': 'pin20'}}

More generally, you could obviously rewrite your existing code to this:

if name not in my_dict:
my_dict[name] = {}
my_dict[name].update({ id : pin }

Whenever you can do that, you can use setdefault. (But notice that we're calling a mutating method or assigning to a key/index/member of my_dict[name] here, not just assigning a new value to my_dict[name]. That's the key to it being useful.)


Of course almost any time you can use setdefault, you can also use defaultdict (as demonstrated in CoryKramer's answer) (and vice-versa). If you want defaulting behavior all the time, use defaultdict. Only use setdefault if you want defaulting behavior just this once (e.g., you want defaulting while building the dict up, but you want KeyErrors later when using it).

How to add values of a key without losing any value in dictionary python when merging two list as dictionary?

Try this:

name = ['A', 'A', 'B', 'B', 'C', 'D', 'D', 'D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
dict = {}
for key, value in zip(name, num):
if key not in dict:
dict[key] = value
else:
dict[key] += value
print(dict)

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
if line[0] in years_dict:
# append the new number to the existing array at this slot
years_dict[line[0]].append(line[1])
else:
# create a new array in this slot
years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
"2010": [2],
"2009": [4,7],
"1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

How can I add a list's items to a key in a dictionary with already existing values?

for i,(k,v) in enumerate(mydic.items()):
mydic[k]=[v,mylist[i]]

Python update a key in dict if it doesn't exist

You do not need to call d.keys(), so

if key not in d:
d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?

Use collections.defaultdict, where the default value is a new list instance.

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

In this way calling .append(...) will always succeed, because in case of a non-existing key append will be called on a fresh empty list.

You can instantiate the defaultdict with a previously generated list, in case you get the dict likes from another source, like so:

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

Note that using list as the default_factory attribute of a defaultdict is also discussed as an example in the documentation.

Appending a dictionary of values to a dictionary of lists with same keys

You can append to a list in this sense like this

dict_v = {'A': 2, 'B': 3, 'C': 4}
dict_l = {'A': [1,3,4], 'B': [8,5,2], 'C': [4,6,2]}

for key in dict_l:
if key in dict_v:
dict_l[key] += [dict_v[key]]
print(dict_l)

The change is that you are appending the value dict_v[key] as a list [dict_v[key]] and appending it to the entries that are already in dict_l[key] using +=. This way you can also append multiple values as a list to an already existing list.



Related Topics



Leave a reply



Submit