DEV Community

loading...
Cover image for How can I add new keys to a Python dictionary?

How can I add new keys to a Python dictionary?

courseprobe profile image Course Probe ・2 min read

In this short tutorial we are going to explore different ways to add values to a dictionary in Python. Some times you create a dictionary in Python and later on on the code or dynamically it is needed to add values or add keys to that dict.

So let’s explore Python dictionary and some examples to append new keys.

Creating an empty dictionary

data = {}
# OR
data = dict()
Enter fullscreen mode Exit fullscreen mode

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}
Enter fullscreen mode Exit fullscreen mode

Inserting/Updating a single value

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
Enter fullscreen mode Exit fullscreen mode

Inserting/Updating multiple values

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

Python 3.9+:

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}
Enter fullscreen mode Exit fullscreen mode

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2
Enter fullscreen mode Exit fullscreen mode

Python 3.5+:

This uses a new feature called dictionary unpacking.

data = {**data1, **data2, **data3}
Enter fullscreen mode Exit fullscreen mode

Python 3.9+:

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}
Enter fullscreen mode Exit fullscreen mode

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary
Enter fullscreen mode Exit fullscreen mode

Check if a key is already in dictionary

key in data
Enter fullscreen mode Exit fullscreen mode

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
Enter fullscreen mode Exit fullscreen mode

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))
Enter fullscreen mode Exit fullscreen mode

Interesting resources:

Get the Book: Python Programming from Scratch

source: https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary


Other Dev posts:

Discussion (0)

pic
Editor guide