Advertisement
Dictionaries are a core part of Python. They let you pair values with unique keys, making your data organized and easy to work with. If you’ve ever built a script, sorted some data, or created a quick lookup table, chances are you’ve used a dictionary. At some point, you’ll probably need to add new keys to one—maybe just one, maybe many. Fortunately, Python gives you several ways to do this. Some are short and clear, others are better when you’re handling more data at once.
There’s no one-size-fits-all method, but each of these options can help depending on what your code looks like and what you're trying to do. Let's look at them one by one.
This is the most common way. You just write the name of the dictionary, put the key in square brackets, and assign it a value.
python
CopyEdit
my_dict = {'apple': 1, 'banana': 2}
my_dict['cherry'] = 3
print(my_dict)
# Output: {'apple': 1, 'banana': 2, 'cherry': 3}
If the key already exists, this will just replace the value. If it doesn’t, it creates a new key and adds it. It’s simple, direct, and probably the clearest way to show what you're doing.
With setdefault(), you don’t have to check if a key exists before adding something. This method will return the value if the key is already there, or create it if it’s not.
python
CopyEdit
inventory = {'pencil': 10}
inventory.setdefault('pen', 5)
print(inventory)
# Output: {'pencil': 10, 'pen': 5}
It's good when you're working in loops or functions where a missing key might cause errors. This way, you make sure the key exists and has a value, without writing an if statement.
Python 3.5 and above support unpacking multiple dictionaries using **. This doesn't change the original dictionary—it gives you a new one.
python
CopyEdit
first = {'a': 1}
second = {'b': 2}
combined = {**first, **second}
print(combined)
# Output: {'a': 1, 'b': 2}
This is useful when you’re creating a new dictionary based on old ones. You might be building settings, filters, or parameters, and you don’t want to overwrite anything until you’re ready.
You can also mix in new values right on the spot:
python
CopyEdit
updated = {**first, 'c': 3}
This way, you’re not editing in place. It’s clean when you want to keep your original untouched.
When your keys are strings that are valid variable names, you can pass them as keyword arguments to dict().
python
CopyEdit
colors = dict(red='#FF0000', green='#00FF00')
print(colors)
# Output: {'red': '#FF0000', 'green': '#00FF00'}
You can then update your original dictionary with these values:
python
CopyEdit
base = {'blue': '#0000FF'}
base.update(colors)
print(base)
# Output: {'blue': '#0000FF', 'red': '#FF0000', 'green': '#00FF00'}
This method is best when you're hardcoding string keys that are short and clear.
If you're adding more than one key-value pair at once, update() makes that easy. You pass another dictionary as the argument, and it adds those keys to the existing one.
python
CopyEdit
data = {'x': 100}
data.update({'y': 200})
print(data)
# Output: {'x': 100, 'y': 200}
You can also combine it with other data sources:
python
CopyEdit
new_items = dict(a=1, b=2)
data.update(new_items)
This is especially useful when your keys and values are already organized into a dictionary, or if you're combining several small dictionaries into one.
If you’re adding keys in a loop, square brackets still work well. You can create keys based on logic, data, or a pattern.
python
CopyEdit
result = {}
for i in range(4):
result[f'item{i}'] = i * 2
print(result)
# Output: {'item0': 0, 'item1': 2, 'item2': 4, 'item3': 6}
This comes in handy when you’re processing data line-by-line or generating a structure based on user input or file content.
You don’t need anything fancy here. Just assign new keys as you go.
If you're collecting items into lists or counting things by category, defaultdict saves time. It creates default values when keys don't exist yet.
python
CopyEdit
from collections import defaultdict
scores = defaultdict(list)
scores['math'].append(90)
scores['math'].append(85)
scores['science'].append(88)
print(scores)
# Output: defaultdict(
You don’t need to write checks to see if the key exists. Just call .append() or .add() or whatever makes sense for your data.
This is especially useful when you’re building dictionaries from raw input like logs, text files, or user responses.
fromkeys() creates a dictionary with a list of keys and assigns them all the same value. You can merge the result into another dictionary if needed.
python
CopyEdit
keys = ['north', 'south']
defaults = dict.fromkeys(keys, 0)
settings = {'east': 1}
settings.update(defaults)
print(settings)
# Output: {'east': 1, 'north': 0, 'south': 0}
This is good when you need to initialize several keys at once, such as setting flags or counters.
Keep in mind: all the keys will get the same value, and if the value is mutable (like a list), all keys will share the same object unless handled carefully.
Python doesn’t force you to stick to one way of adding keys. Whether you're assigning a value directly, updating in bulk, or building things out in loops, you’ve got options. Some of these methods make more sense when you’re creating a new dictionary, others are better when you're updating one.
If you’re after clarity, go with square brackets. If you’re collecting groups or want to avoid errors with missing keys, defaultdict or setdefault() can help. And if you're building things programmatically or pulling from multiple places, unpacking or using .update() might keep your code cleaner.
Advertisement
Explore effective ways for scatter plot visualization in Python using matplotlib. Learn to enhance your plots with color, size, labels, transparency, and 3D features for better data insights
Learn how AI parameters impact model performance and how to optimize them for better accuracy, efficiency, and generalization
Jio Brain by Jio Platforms brings seamless AI integration to Indian enterprises by embedding intelligence into existing systems without overhauls. Discover how it simplifies real-time data use and smart decision-making
Learn how to convert strings to JSON objects using tools like JSON.parse(), json.loads(), JsonConvert, and more across 11 popular programming languages
Learn how Intel Core Ultra CPUs use advanced neural processing to unlock faster and more responsive AI experiences on PC.
Learn different methods to calculate the average of a list in Python. Whether you're new or experienced, this guide makes finding the Python list average simple and clear
How to add strings in Python using 8 clear methods like +, join(), and f-strings. This guide covers everything from simple concatenation to building large text efficiently
Create user personas for ChatGPT to improve AI responses, boost engagement, and tailor content to your audience.
Looking for the best AI resume builders? Check out these 10 free tools that help you craft professional resumes that stand out and get noticed by employers
Stay informed with the best AI news websites. Explore trusted platforms that offer real-time AI updates, research highlights, and expert insights without the noise
Learn how sorting lists in Python using sort() can help organize data easily. This beginner-friendly guide covers syntax, examples, and practical tips using the Python sort method
Learn 8 effective methods to add new keys to a dictionary in Python, from square brackets and update() to setdefault(), loops, and defaultdict