Python dict how to create key or append an element to key?

python dictionary append value
python add to dictionary in loop
python dictionary append value to key
python dictionary add key-value pair
append dictionary to list python
python dictionary add value to existing key
python add multiple items to dictionary
python dynamically create dictionary key

I have an empty dictionary. Name: dict_x It is to have keys of which values are lists.

From a separate iteration, I obtain a key (ex: key_123), and an item (a tuple) to place in the list of dict_x's value key_123.

If this key already exists, I want to append this item. If this key does not exist, I want to create it with an empty list and then append to it or just create it with a tuple in it.

In future when again this key comes up, since it exists, I want the value to be appended again.

My code consists of this:

Get key and value.

See if NOT key exists in dict_x.

and if not create it: dict_x[key] == []

Afterwards: dict_x[key].append(value)

Is this the way to do it? Shall I try to use try/except blocks?

Use dict.setdefault():

dic.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

Python dict how to create key or append an element to key?, The main differentiating factor between a list and a dictionary would be, that instead of the index we use keys to access the elements of a dictionary (or values to  From a separate iteration, I obtain a key (ex: key_123), and an item (a tuple) to place in the list of dict_x‘s value key_123. If this key already exists, I want to append this item. If this key does not exist, I want to create it with an empty list and then append to it or just create it with a tuple in it.

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

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

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

Python Dictionaries, Python dictionary provides a member function update() i.e. For each entry in sequence, it will add the given key value pair in dictionary and if key already exists then it Adding a list of tuples (key value pairs) in dictionary. Varun May 20, 2018 Python : How to add / append key value pairs in dictionary using dict.update() 2019-10-19T13:45:24+05:30 dictionary, Python 4 Comments In this article we will discuss how to add or append new key value pairs in a dictionary and also how to update value of existing keys.

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

Python : How to add / append key value pairs in dictionary using dict , How do you add multiple values to a key in Python? Add New Element With New Key in Dictionary Using Python You can also add new items to the Dictionary in Python. To perform adding new items, you have to use the update() function of Python. The function takes Dictionary item as the argument to pass which you want to append.

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

Python Dictionary, This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value. This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn’t exist, it will be added and will point to that value. If the key exists, the current value it points to will be overwritten. dict = {'key1':'geeks', 'key2':'fill_me'}.

Python add to Dictionary, Notice that 'c' value is not changed because of if condition. That's all for adding keys to a dictionary in python. @user1162512 if you want to have more than one value for a certain key, then you'll need to use a list or some other container for multiple values (another dict, a tuple, etc.). You can't do {"abc": 1, 2} as a dict is a key:value pair, with only one value per key.

In the Python dictionary, can 1 key hold more than 1 value?, Extend the list by appending all the items from the iterable. List comprehensions provide a concise way to create lists. Common The main operations on a dictionary are storing a value with some key and extracting the value given the key. I want to add an item to an existing dictionary in python. For example, this is my dictionary: How to achieve this? i cant believe this inline solution hasn't been posted yet. We can use { **default_data, 'item3':3} which returns the updated array. Very useful for lambda functions and list comprehensions. (requires PEP 448 (Python 3.5

Can a dictionary have two keys of the same value?, Python dictionaries are an unordered collection of key value pairs. In this We add a new element to the dictionary by using a new key as a subscript and assigning it a value. 34 print "After adding" print(CountryCodeDict) We can also append elements to a dictionary by merging two dictionaries. Accessing elements of a dictionary. Elements stored in a dictionary can be accessed just like lists in python, i.e, using the for loop. However, while iterating over each element, we will get the key and not the value of the element, therefore, to access the value of the element, we have to use the key just like index, For example: myDictionary[key].

Comments
  • I used to do this by dict_x[key] = [some_value] if not dict_x.has_key(key) else dict_x[key] + [some_value] but this answer suggests a far better way. In fact it gets set() as an argument and allows you to use add() method...
  • Hello, why do you think .setdefault creates unnecessary dictionaries?
  • I don't think .setdefault() creates unnecessary dictionaries. I think I'm creating unnecessary lists (i.e. []) in the second argument of .setdefault() that's never used if key already exists. I could use dict.setdefault() (for the benefit of efficient key hashing), and use a variable to reuse unused lists but that adds a few more lines of code.
  • IIRC, in Python an empty list in an equality is considered a constant at the bytecode level, but this needs some confirmation by a bytecode guru (or just use the disas module).
  • Using .setdefault creates a regular dict where absent key look-up will result in a KeyError while collections.defaultdict(list) creates a dict where absent key lookups will insert an empty list-- i think you should choose based on which behaviour you want