In Python, a dictionary is a collection of key-value pairs, where each key is unique and corresponds to a specific value.
To change the value associated with a specific key in a dictionary, you can use the following syntax:
my_dict[key] = new_value
where my_dict
is the name of the dictionary, key
is the key whose value you want to change, and new_value
is the new value you want to assign to that key.
For example, if you have a dictionary my_dict
with the key-value pair {'a': 1, 'b': 2}
, you can change the value associated with the key 'a'
to 3
using the following code:
my_dict[‘a’] = 3
After executing this code, the dictionary my_dict
would be {'a': 3, 'b': 2}
.
You can also use the update()
method to change multiple values in a dictionary at once. The update()
method takes another dictionary as an argument and updates the keys in the calling dictionary with the values from the argument dictionary. For example, you can update the values of keys 'a'
and 'b'
in the dictionary my_dict
with the following code:
my_dict.update({‘a’: 4, ‘b’: 5})
After executing this code, the dictionary my_dict
would be {'a': 4, 'b': 5}
.
You can change dictionary items in Python using either the square bracket notation or the update()
method.
Here’s an example of using square brackets to change a dictionary item:
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict[‘apple’] = 5
print(my_dict) # Output: {‘apple’: 5, ‘banana’: 3, ‘orange’: 4}
In the above example, we change the value associated with the key 'apple'
from 2
to 5
.
Here’s an example of using the update()
method to change dictionary items:
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict.update({‘apple’: 5, ‘banana’: 6})
print(my_dict) # Output: {‘apple’: 5, ‘banana’: 6, ‘orange’: 4}
In the above example, we use the update()
method to change the values associated with the keys 'apple'
and 'banana'
from 2
and 3
to 5
and 6
, respectively.
You can also add new key-value pairs using the same syntax:
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict[‘pear’] = 1
print(my_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4, ‘pear’: 1}
In the above example, we add a new key-value pair 'pear': 1
to the dictionary my_dict
.
Here are some more examples of changing dictionary items in Python:
update()
method with another dictionary:my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
new_items = {‘apple’: 5, ‘banana’: 6, ‘pear’: 1}
my_dict.update(new_items)
print(my_dict) # Output: {‘apple’: 5, ‘banana’: 6, ‘orange’: 4, ‘pear’: 1}
In this example, we use the update()
method with the dictionary new_items
to change the values associated with the keys 'apple'
and 'banana'
, and add a new key-value pair 'pear': 1'
.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
for key in my_dict:
my_dict[key] *= 2
print(my_dict) # Output: {‘apple’: 4, ‘banana’: 6, ‘orange’: 8}
In this example, we use a for
loop to iterate over the keys in the dictionary my_dict
, and multiply each value by 2
to change the items in-place.
my_dict = {‘fruits’: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}}
my_dict[‘fruits’][‘apple’] = 5
print(my_dict) # Output: {‘fruits’: {‘apple’: 5, ‘banana’: 3, ‘orange’: 4}}
In this example, we have a nested dictionary my_dict
with a key 'fruits'
that contains another dictionary of fruit counts. We use the square bracket notation to change the value associated with the key 'apple'
from 2
to 5
within the nested dictionary.
del
keyword:In this example, we use the del
keyword to remove the key-value pair associated with the key 'banana'
from the dictionary my_dict
.
def add_one(value):
return value + 1
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict = {k: add_one(v) for k, v in my_dict.items()}
print(my_dict) # Output: {‘apple’: 3, ‘banana’: 4, ‘orange’: 5}
In this example, we define a function add_one
that takes a value and returns the value plus 1
. We then use a dictionary comprehension to apply the function to each value in the dictionary my_dict
and create a new dictionary with the updated values.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict = {v: k for k, v in my_dict.items()}
print(my_dict) # Output: {2: ‘apple’, 3: ‘banana’, 4: ‘orange’}
In this example, we use a dictionary comprehension to create a new dictionary with the keys and values swapped from the dictionary my_dict
. The keys in the new dictionary are the values from the original dictionary, and the values are the keys from the original dictionary.
pop()
method to remove and return an item:my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
removed_item = my_dict.pop(‘banana’)
print(removed_item) # Output: 3
print(my_dict) # Output: {‘apple’: 2, ‘orange’: 4}
In this example, we use the pop()
method to remove the key-value pair associated with the key 'banana'
from the dictionary my_dict
, and assign the value 3
to the variable removed_item
.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
In this example, we use the sorted()
function to sort the items in the dictionary my_dict
by key, and then create a new dictionary with the sorted items using a dictionary comprehension.
|
operator (Python 3.9+):my_dict1 = {‘apple’: 2, ‘banana’: 3}
my_dict2 = {‘orange’: 4, ‘pear’: 1}
merged_dict = my_dict1 | my_dict2
print(merged_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4, ‘pear’: 1}
In this example, we use the |
operator to merge two dictionaries my_dict1
and my_dict2
into a new dictionary merged_dict
. If there are any duplicate keys between the two dictionaries, the values from the second dictionary (my_dict2
) will overwrite the values from the first dictionary (my_dict1
).
update()
method to add or update items:my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict.update({‘apple’: 5, ‘kiwi’: 1})
print(my_dict) # Output: {‘apple’: 5, ‘banana’: 3, ‘orange’: 4, ‘kiwi’: 1}
In this example, we use the update()
method to add or update items to the dictionary my_dict
. The method takes a dictionary as its argument, and any key-value pairs that already exist in the dictionary are updated with the new values. Any new key-value pairs are added to the dictionary.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4, ‘kiwi’: 1}
filtered_dict = {k: v for k, v in my_dict.items() if v > 2}
print(filtered_dict) # Output: {‘banana’: 3, ‘orange’: 4}
In this example, we use a dictionary comprehension to create a new dictionary filtered_dict
that contains only the key-value pairs from my_dict
where the value is greater than 2
.
fruits = [‘apple’, ‘banana’, ‘orange’]
quantities = [2, 3, 4]
my_dict = dict(zip(fruits, quantities))
print(my_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
In this example, we use the zip()
function to combine the two lists fruits
and quantities
into a list of tuples, where each tuple contains a fruit and its corresponding quantity. We then use the dict()
function to create a dictionary from the list of tuples.
In this example, we use a dictionary to remove duplicates from the list my_list
while preserving the order of the remaining items. We create an empty dictionary my_dict
, and iterate over each item in my_list
. For each item, we check if it is already in my_dict
. If it is not, we add it to my_dict
with a value of True
(the value is not important, as we are only interested in the keys). We also append the item to a new list my_list_no_duplicates
. If the item is already in my_dict
, we skip it.
my_dict = {‘Apple’: 2, ‘Banana’: 3, ‘Orange’: 4}
my_dict_lower = {k.lower(): v for k, v in my_dict.items()}
print(my_dict_lower) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
In this example, we use a dictionary comprehension to create a new dictionary my_dict_lower
that contains the same key-value pairs as my_dict
, but with all keys converted to lowercase. We iterate over the key-value pairs in my_dict
, and for each pair we create a new key-value pair in my_dict_lower
where the key is the lowercase version of the original key.
my_list = [(‘apple’, 2), (‘banana’, 3), (‘orange’, 4), (‘kiwi’, 1), (‘banana’, 2)]
my_dict = {}
for item in my_list:
if item[0] not in my_dict:
my_dict[item[0]] = [item[1]]
else:
my_dict[item[0]].append(item[1])
print(my_dict) # Output: {‘apple’: [2], ‘banana’: [3, 2], ‘orange’: [4], ‘kiwi’: [1]}
In this example, we use a dictionary to group a list of tuples my_list
by a common key (the first element of each tuple). We create an empty dictionary my_dict
, and iterate over each tuple in my_list
. For each tuple, we check if the first element (the key) is already in my_dict
. If it is not, we add it to my_dict
with a value of a list containing the second element of the tuple. If the key is already in my_dict
, we append the second element of the tuple to the existing list of values for that key.
dict1 = {‘apple’: 2, ‘banana’: 3}
dict2 = {‘orange’: 4, ‘kiwi’: 1}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4, ‘kiwi’: 1}
In this example, we use the **
operator to merge two dictionaries dict1
and dict2
into a new dictionary merged_dict
. The **
operator unpacks the key-value pairs of each dictionary into a single dictionary.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
reversed_dict = {v: k for k, v in my_dict.items()}
print(reversed_dict) # Output: {2: ‘apple’, 3: ‘banana’, 4: ‘orange’}
In this example, we use a dictionary comprehension to create a new dictionary reversed_dict
that contains the same key-value pairs as my_dict
, but with the keys and values swapped. We iterate over the key-value pairs in my_dict
, and for each pair we create a new key-value pair in reversed_dict
where the key is the value of the original pair, and the value is the key of the original pair.
my_list = [{‘name’: ‘Alice’, ‘age’: 25}, {‘name’: ‘Bob’, ‘age’: 30}]
my_dict = {d[‘name’]: d for d in my_list}
print(my_dict) # Output: {‘Alice’: {‘name’: ‘Alice’, ‘age’: 25}, ‘Bob’: {‘name’: ‘Bob’, ‘age’: 30}}
In this example, we use a dictionary comprehension to create a new dictionary my_dict
that contains the same data as my_list
, but organized as a dictionary of dictionaries. We iterate over each dictionary d
in my_list
, and for each dictionary we create a new key-value pair in my_dict
where the key is the value of the name
key in d
, and the value is d
itself.
update()
method:my_dict = {‘apple’: 2, ‘banana’: 3}
my_dict.update({‘orange’: 4})
print(my_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
In this example, we use the update()
method to add a new key-value pair to the my_dict
dictionary. We pass a new dictionary with a single key-value pair {'orange': 4}
as an argument to update()
, which adds this pair to my_dict
.
pop()
method:my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
my_dict.pop(‘banana’)
print(my_dict) # Output: {‘apple’: 2, ‘orange’: 4}
In this example, we use the pop()
method to remove a key-value pair from the my_dict
dictionary. We pass the key 'banana'
as an argument to pop()
, which removes the corresponding key-value pair from my_dict
.
my_dict = {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print(sorted_dict) # Output: {‘apple’: 2, ‘banana’: 3, ‘orange’: 4}
In this example, we use the sorted()
function to sort the key-value pairs in the my_dict
dictionary by their values. We pass the my_dict.items()
iterable to sorted()
to get a list of key-value pairs, and then use a lambda function to extract the value of each pair for sorting. Finally, we convert the sorted list of pairs back into a dictionary using the dict()
constructor. Note that dictionaries in Python are not ordered by default, so the order of the key-value pairs in the resulting sorted_dict
dictionary may not be the same as in my_dict
.