Python Dictionary Methods



Python dictionaries are versatile data structures that store key-value pairs. Here are some commonly used methods and operations associated with dictionaries:

1. Creating a Dictionary:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

2. Accessing Values:

value = my_dict['key1']

# or

value = my_dict.get('key1', default_value)

3. Adding or Updating Items:

my_dict['new_key'] = 'new_value'  # Adding a new key-value pair

my_dict.update({'key1': 'new_value', 'key4': 'value4'})  # Updating existing or adding new key-value pairs

4. Removing Items:

del my_dict['key1']  # Remove a specific key-value pair

value = my_dict.pop('key2')  # Remove and return the value for a given key

my_dict.clear()  # Remove all items in the dictionary

5. Checking if a Key Exists:

if 'key1' in my_dict:

    # Do something

6. Iterating Through Keys and Values:

for key in my_dict:

    print(key, my_dict[key])


# or using items()

for key, value in my_dict.items():

    print(key, value)

7. Dictionary Length:

length = len(my_dict)

8. Copying a Dictionary:

copy_dict = my_dict.copy()  # Shallow copy

9. Merging Dictionaries:

new_dict = {**dict1, **dict2}  # Requires Python 3.5 and above

# or

new_dict = dict1.copy()

new_dict.update(dict2)

10. Dictionary Comprehension:

squared_values = {key: value ** 2 for key, value in my_dict.items()}

11. Getting Keys and Values:

keys = my_dict.keys()

values = my_dict.values()

12. Set Default Value:

value = my_dict.setdefault('new_key', 'default_value')

13. Sorting:

Dictionaries are inherently unordered. To sort by keys or values, you can create a sorted list of items.

sorted_items = sorted(my_dict.items())  # Sort by keys

sorted_items_by_value = sorted(my_dict.items(), key=lambda x: x[1])  # Sort by values

These are just some of the commonly used methods with dictionaries in Python. Understanding these methods will help you effectively work with dictionaries in your Python programs.

Post a Comment

Previous Post Next Post