Python

Python dict : How to append and update elements

arage.com@gmail.com

A Python dictionary (dict) is a data structure for storing pairs of keys and values.I will explain how to add and update elements in a dict.

How to Add Elements to a Python Dictionary (dict)

Basic Method of Adding Elements

The most basic way to add an element to a Python dictionary is to directly specify a new key and value.

1my_dict = {}
2my_dict["key1"] = "value1"
3print(my_dict)  # {'key1': 'value1'}

Adding Elements Using setdefault()

The setdefault() method allows you to add a new entry only if the specified key does not already exist in the dictionary.

1my_dict = {"key1": "value1"}
2my_dict.setdefault("key2", "value2")
3print(my_dict)  # {'key1': 'value1', 'key2': 'value2'}

Adding Elements Using update()

The update() method allows you to add elements from another dictionary.

1my_dict = {"key1": "value1"}
2my_dict.update({"key2": "value2"})
3print(my_dict)  # {'key1': 'value1', 'key2': 'value2'}

How to Update Elements of a Python Dictionary (dict)

Updating an element of a dictionary is done in the same way as adding a new element; you specify the key and set the value.

1my_dict = {"key1": "value1"}
2my_dict["key1"] = "new_value1"
3print(my_dict)  # {'key1': 'new_value1'}

How to Merge Python Dictionaries (dict)

Merging Dictionaries Using update()

The update() method can be used to merge two dictionaries.

1dict1 = {"key1": "value1"}
2dict2 = {"key2": "value2"}
3dict1.update(dict2)
4print(dict1)  # {'key1': 'value1', 'key2': 'value2'}

Merging Methods since Python3.5: {}, dict(), |, |= operators

Since Python 3.5, dictionaries can be merged using the {}, dict(), |, and |= operators.

1dict1 = {"key1": "value1"}
2dict2 = {"key2": "value2"}
3combined_dict = {**dict1, **dict2}
4print(combined_dict)  # {'key1': 'value1', 'key2': 'value2'}

And from Python 3.9 onwards, the more intuitive | operator can be used for merging.

1dict1 = {"key1": "value1"}
2dict2 = {"key2": "value2"}
3combined_dict = dict1 | dict2
4print(combined_dict)  # {'key1': 'value1', 'key2': 'value2'}

Handling Duplicate Keys

If a key is duplicated in a dictionary, the new value overwrites the old one. This is because dictionaries guarantee the uniqueness of keys.

1dict1 = {"key1": "value1"}
2dict2 = {"key1": "new_value1"}
3dict1.update(dict2)
4print(dict1)  # {'key1': 'new_value1'}
記事URLをコピーしました