How can I add new keys to a dictionary? How can I add new keys to a dictionary? python python

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.

To add multiple keys simultaneously, use dict.update():

>>> x = {1:2}>>> print(x){1: 2}>>> d = {3:4, 5:6, 7:8}>>> x.update(d)>>> print(x){1: 2, 3: 4, 5: 6, 7: 8}

For adding a single key, the accepted answer has less computational overhead.

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}# ORdata = dict()

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}# ORdata = dict(a=1, b=2, c=3)# ORdata = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

Inserting/Updating a single value

data['a'] = 1  # Updates if 'a' exists, else adds 'a'# ORdata.update({'a': 1})# ORdata.update(dict(a=1))# ORdata.update(a=1)

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}

Creating a merged dictionary without modifying originals

data3 = {}data3.update(data)  # Modifies data3, not datadata3.update(data2)  # Modifies data3, not data2

Python 3.5+:

This uses a new feature called dictionary unpacking.

data = {**data1, **data2, **data3}

Python 3.9+:

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionarydata.pop(key)  # Removes the key & returns the valuedata.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the valuesfor key, value in d.items(): # Iterates through the pairsfor key in d.keys(): # Iterates just through key, ignoring the valuesfor value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))