120 Dictionary Operations in Python

120 Dictionary Operations in Python

Dictionary is one of the most powerful and commonly used data structures in Python. It stores data in the form of key-value pairs, providing fast data lookup capabilities. This article will comprehensively introduce 120 dictionary operation methods, covering basic operations, advanced techniques, and practical application scenarios to help master this important data structure.

Previous Python readings >>

15 Python Libraries for Automated Financial Data Retrieval

30 Efficient Automation Scripts for Processing Financial Excel Data

25 Practical Automation Office Codes, Ready to Use

30 Methods for Automated Image Processing in Office with Python

30 Common Functions for Data Analysis with Python Pandas

Quickly Develop a Web File Server with Python

Parse and Convert JSON Format with Python

15 Automation Scripts for Processing Excel Data with Python

Batch Automation to Add Watermarks to Images with Python

10 Examples of Data Visualization Automation with Python (Including Code), Highly Recommended

Automate PDF Operations with Python

15 Efficient and Practical Automation Libraries for Python

20 Practical and Efficient Decorators in Python

Automate Word Operations with Python

Efficiently Handle 40 Tasks in One Line of Python Code

15 Common Scripts in Python

Functional Programming in Python

Automate Text File Operations with Python

The Amazing Library for Developing AI Applications in Python! Gradio

Automate Excel Operations with Python

Data Type Operations in Python

1. Dictionary Creation Methods

1.Create an Empty Dictionary Using Curly Braces

empty_dict = {}

This is the most concise way to create an empty dictionary.

2.Create an Empty Dictionary Using the dict() Constructor

empty_dict = dict()

This is equivalent to the curly braces method but is not as concise.

3.Create a Dictionary by Direct Assignment

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

This is the most commonly used method to create a dictionary.

4.Create a Dictionary from a Sequence of Key-Value Pairs Using dict()

person = dict([('name', 'Alice'), ('age', 25), ('city', 'New York')])

This is suitable for situations where you already have a sequence of key-value pairs.

5.Create a Dictionary Using Keyword Arguments

person = dict(name='Alice', age=25, city='New York')

The syntax is more concise, and keys do not need quotes.

6.Create a Dictionary with Mixed Key Types

mixed_keys = {'name': 'Bob', 42: 'answer', (1, 2): 'tuple as key'}

Keys can be strings, numbers, or tuples, etc., of immutable types.

7.Create a Default Value Dictionary Using fromkeys()

default_dict = dict.fromkeys(['a', 'b', 'c'], 0)

Quickly create a dictionary with the same default value.

8.Create a Dictionary from Two Lists Using zip()

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))

A convenient way to merge two lists into a dictionary.

9.Create a Dictionary Using Dictionary Comprehension

squares = {x: x**2 for x in range(5)}

Create a dictionary concisely and efficiently.

10.Create a Dictionary with Conditional Filtering

numbers = [1,2,3,4,5,6]
result = {x: x**2 for x in numbers if x % 2 == 0}

Only includes elements that meet the condition.

2. Dictionary Access Methods

11.Access Value Directly by Key

print(person['name'])  # Alice

A KeyError will be raised if the key does not exist.

12.Safely Access Using get() Method

print(person.get('age'))      # 25
print(person.get('gender'))   # None

Returns None without raising an error if the key does not exist.

13.get() Method with Default Value

print(person.get('gender', 'unknown'))  # Returns default value 'unknown'

Returns a specified default value if the key does not exist.

14.Use setdefault() to Get and Set Default Value

value = person.setdefault('phone', '123-456-7890')

Adds the key to the dictionary and sets a default value if it does not exist.

15.Check if Key Exists

if 'name' in person:
    print(person['name'])

Use the in operator to check if the key exists.

16.Check if Key Does Not Exist

if 'gender' not in person:
    print('gender key not found')

Use the not in operator.

17.Check if Value Exists

if 25 in person.values():
    print('25 is one of the values')

Check if a value exists in the dictionary.

18.Handle Missing Keys with try-except

try:
    value = person['gender']
except KeyError:
    value = 'default'

Catch KeyError exceptions to handle missing keys.

19.Safely Access Nested Dictionaries

city = people.get('Alice', {}).get('city', 'Unknown')

Avoid KeyError when accessing nested dictionaries.

20.Use collections.defaultdict to Handle Missing Keys

from collections import defaultdict
my_dict = defaultdict(int)
my_dict['a'] += 1  # Automatically initialized to 0

Provide default values for non-existent keys.

3. Dictionary Modification Methods

21.Add New Key-Value Pair

person['email'] = '[email protected]'

This is an addition operation when the key does not exist.

22.Modify Existing Value

person['age'] = 26

This is a modification operation when the key exists.

23.Merge Dictionaries Using update()

person.update({'city': 'New York', 'age': 26})

Batch update multiple key-value pairs.

24.Conditionally Update Values Using update()

my_dict.update((k, v*2) for k, v in my_dict.items() if condition)

Update values in the dictionary based on conditions.

25.Update Values Based on Another Dictionary

dict1.update((k, dict1[k]+dict2[k]) for k in dict1.keys() & dict2.keys())

Update dict1 based on corresponding values in dict2.

26.Merge Dictionaries Using Dictionary Unpacking

merged_dict = {**dict1, **dict2}

A concise merging method supported in Python 3.5+

27.Merge Dictionaries Using the | Operator

merged_dict = dict1 | dict2

A new merging operator introduced in Python 3.9+

28.Merge Dictionaries Using collections.ChainMap

from collections import ChainMap
combined = dict(ChainMap(dict1, dict2))

Logically merge without creating a new dictionary.

29.Use pop() to Remove and Return Value

age = person.pop('age')

Remove the key and return the corresponding value.

30.pop() with Default Value

gender = person.pop('gender', 'unknown')

Returns the default value without raising an error if the key does not exist.

4. Dictionary Traversal Methods

31.Iterate Over All Keys

for key in person:
    print(key, person[key])

The most basic way to traverse a dictionary.

32.Explicitly Iterate Over Keys

for key in person.keys():
    print(key)

More explicit using the keys() method.

33.Iterate Over All Values

for value in person.values():
    print(value)

Focus only on the values in the dictionary.

34.Iterate Over Key-Value Pairs

for key, value in person.items():
    print(f"{key}: {value}")

The most common way to get both keys and values simultaneously.

35.Reverse Iterate the Dictionary

for key in reversed(person):
    print(key, person[key])

Python 3.7+ maintains insertion order, allowing reverse iteration.

36.Ordered Iteration Over Keys

for key in sorted(person):
    print(key, person[key])

Iterate after sorting by key.

37.Sort and Iterate by Value

for key, value in sorted(person.items(), key=lambda x: x[1]):
    print(key, value)

Iterate after sorting by value.

38.Conditional Filtering Iteration

for key, value in person.items():
    if value > 20:
        print(key, value)

Only iterate over elements that meet the condition.

39.Use enumerate to Iterate

for i, (key, value) in enumerate(person.items()):
    print(i, key, value)

Simultaneously get the index and key-value pairs.

40.Batch Processing Iteration

from itertools import islice
batch_size = 10
for batch in iter(lambda: list(islice(person.items(), batch_size)), []):
    process_batch(batch)

Batch processing when handling large dictionaries.

5. Dictionary Conversion Methods

41.Convert to a List of Keys

keys = list(person.keys())

Get a list of all keys in the dictionary.

42.Convert to a List of Values

values = list(person.values())

Get a list of all values in the dictionary.

43.Convert to a List of Key-Value Pairs

items = list(person.items())

Get a list of (key, value) tuples.

44.Convert to JSON String

import json
json_str = json.dumps(person)

Convert between dictionary and JSON string.

45.Load from JSON String

person = json.loads(json_str)

Convert JSON string back to dictionary.

46.Convert Dictionary Keys to Strings

str_dict = {str(key): value for key, value in person.items()}

Ensure all keys are of string type.

47.Convert Dictionary Value Types

int_values = {k: int(v) for k, v in person.items()}

Convert all values to a specific type.

48.Convert to Named Tuple

from collections import namedtuple
Person = namedtuple('Person', person.keys())
person_nt = Person(**person)

Convert dictionary to named tuple for easier access.

49.Convert to pandas DataFrame

import pandas as pd
df = pd.DataFrame(list(person.items()), columns=['key', 'value'])

Convert dictionary to DataFrame for analysis.

50.Invert Key-Value Pairs

inverted = {v: k for k, v in person.items()}

Swap the positions of keys and values.

51.Conditional Filtering Conversion

filtered = {k: v for k, v in person.items() if v > 20}

Only keep key-value pairs that meet the condition.

52.Rename Keys Conversion

renamed = {'new_'+k: v for k, v in person.items()}

Batch modify key names.

53.Value Mapping Conversion

mapped = {k: func(v) for k, v in person.items()}

Apply function transformation to all values.

54.Flatten Nested Dictionaries

flat = {k+'_'+k2: v2 for k, nested in person.items() for k2, v2 in nested.items()}

Flatten multi-level nested dictionaries.

55.Create Dictionary from List of Tuples

tuple_list = [('a', 1), ('b', 2)]
dict_from_tuples = dict(tuple_list)

Convert list of tuples to dictionary.

56.Convert Dictionary to String

dict_str = str(person)

Get the string representation of the dictionary.

57.Convert Dictionary to Set

keys_set = set(person.keys())

Get a set of keys for set operations.

58.Remove Duplicate Values from Dictionary

unique_values = set(person.values())

Get a set of unique values.

59.Use map to Transform All Values

transformed = dict(map(lambda item: (item[0], func(item[1])), person.items()))

Functional programming way to transform values.

60.Group Dictionary

from itertools import groupby
grouped = {k: list(v) for k, v in groupby(sorted(items, key=key_func), key=key_func)}

Group dictionary by specific conditions.

6. Advanced Dictionary Techniques

61.Nested Dictionary Operations

employees = {
    'Alice': {'age': 25, 'position': 'Developer'},
    'Bob': {'age': 30, 'position': 'Manager'}
}
print(employees['Alice']['age'])

Handle multi-level nested dictionaries.

62.Safe Access to Nested Dictionaries

age = employees.get('Alice', {}).get('age', 0)

Avoid KeyError when accessing nested dictionaries.

63.Conditional Filtering with Dictionary Comprehension

high_grades = {k: v for k, v in grades.items() if v >= 90}

Filter dictionary elements based on conditions.

64.Key-Value Transformation with Dictionary Comprehension

squared = {k: v**2 for k, v in original.items()}

Transform keys or values.

65.Dictionary View Operations

keys_view = person.keys()
values_view = person.values()
items_view = person.items()

Get dynamic view objects of the dictionary.

66.Set Operations on Dictionary Views

common_keys = dict1.keys() & dict2.keys()
unique_items = dict1.items() - dict2.items()

Perform set operations on dictionary views.

67.Sorting Operations on Dictionaries

sorted_by_key = dict(sorted(person.items()))
sorted_by_value = dict(sorted(person.items(), key=lambda x: x[1]))

Sort dictionaries by keys or values.

68.Dictionary Intersection

common = dict(dict1.items() & dict2.items())

Find common key-value pairs between two dictionaries.

69.Dictionary Difference

difference = dict(dict1.items() - dict2.items())

Find unique key-value pairs in dict1.

70.Dictionary Symmetric Difference

sym_diff = dict(dict1.items() ^ dict2.items())

Find key-value pairs that are different between two dictionaries.

71.Dictionary Merge Conflict Resolution

merged = {**dict1, **dict2, **dict3}

The values of the latter dictionary will overwrite those of the former.

72.Conditional Merge of Dictionaries

merged = {k: dict1.get(k, 0) + dict2.get(k, 0) for k in set(dict1) | set(dict2)}

Perform specific operations on values during merging.

73.Batch Update of Dictionaries

updates = {'a': 1, 'b': 2}
person.update(updates)

Batch update multiple key-value pairs.

74.Extract Subset of Dictionary

subset = {k: person[k] for k in ['name', 'age'] if k in person}

Extract a sub-dictionary with specified keys.

75.Key Remapping of Dictionary

key_map = {'old_key': 'new_key'}
remapped = {key_map.get(k, k): v for k, v in person.items()}

Batch rename dictionary keys.

76.Count Values in Dictionary

from collections import Counter
value_counts = Counter(person.values())

Count the frequency of values in the dictionary.

77.Check Memory Usage of Dictionary

import sys
size = sys.getsizeof(person)

Get the memory size occupied by the dictionary.

78.Compare Dictionaries

are_equal = dict1 == dict2

Compare if two dictionaries are the same.

79.Shallow Copy of Dictionary

copy_dict = person.copy()

Create a shallow copy of the dictionary.

80.Deep Copy of Dictionary

import copy
deep_copy = copy.deepcopy(person)

Create a deep copy of the dictionary, suitable for nested dictionaries.

81.Prefix Handling of Dictionary Keys

prefixed = {'prefix_'+k: v for k, v in person.items()}

Add a prefix to all keys.

82.Suffix Handling of Dictionary Keys

suffixed = {k+'_suffix': v for k, v in person.items()}

Add a suffix to all keys.

83.Case Conversion of Dictionary Keys

lower_keys = {k.lower(): v for k, v in person.items()}

Standardize the case of keys.

84.Case Conversion of Dictionary Values

upper_values = {k: v.upper() if isinstance(v, str) else v for k, v in person.items()}

Standardize the case of string values.

85.Type Conversion of Dictionary Keys

str_keys = {str(k): v for k, v in person.items()}

Ensure all keys are of string type.

86.Type Conversion of Dictionary Values

int_values = {k: int(v) for k, v in person.items() if str(v).isdigit()}

Convert values to integer type.

87.Conditional Key-Value Swapping in Dictionary

swapped = {v: k for k, v in person.items() if isinstance(v, (int, float, str))}

Only swap key-value pairs that meet the condition.

88.Group and Aggregate Dictionary

from collections import defaultdict
grouped = defaultdict(list)
for k, v in data:
    grouped[k].append(v)

Group by key and aggregate values.

89.Key with Maximum Value in Dictionary

max_key = max(person, key=lambda k: person[k])

Find the key with the maximum value.

90.Key with Minimum Value in Dictionary

min_key = min(person, key=lambda k: person[k])

Find the key with the minimum value.

7. Practical Applications of Dictionaries

91.Count Word Frequency

word_count = {}
for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1

A classic application for counting word frequency.

92.Parse JSON Data

import json
with open('data.json') as f:
    data = json.load(f)

Dictionaries are the natural structure for handling JSON data.

93.Configuration File Handling

config = {
    'database': {
        'host': 'localhost',
        'port': 5432,
        'user': 'admin'
    }
}

Manage configurations using nested dictionaries.

94.Cache Implementation

cache = {}
def get_data(key):
    if key not in cache:
        cache[key] = load_data(key)
    return cache[key]

A simple in-memory cache implementation.

95.Data Indexing

index = {}
for i, record in enumerate(data):
    index[record['id']] = i

Create a quick lookup index for data.

96.Attribute Storage

class AttrDict(dict):
    def __getattr__(self, key):
        return self[key]

Access dictionary keys through attributes.

97.Enum Replacement

Colors = {'RED': 1, 'GREEN': 2, 'BLUE': 3}

Implementation of simple enumeration functionality.

98.Data Grouping

grouped = defaultdict(list)
for item in data:
    grouped[item['category']].append(item)

Group data by category.

99.Data Transformation

mapping = {'A': 'Excellent', 'B': 'Good'}
converted = [mapping.get(grade, 'Unknown') for grade in grades]

Transform data values using a mapping.

100.Command Dispatching

from typing import Callable, Dict

def cmd_help() -> None:
    print("help: show this message")

def cmd_exit() -> None:
    print("bye!")
    exit()

commands: Dict[str, Callable[[], None]] = {"help": cmd_help, "exit": cmd_exit}

# Call at runtime
commands[command]()

Manage commands using a dictionary.

101.State Management

state: dict = {"logged_in": False, "user": None}

Manage application state using a dictionary.

102.Data Cleaning

clean_data = {k: clean_func(v) for k, v in raw_data.items()}     # type: ignore

Clean data using a function.

103.Data Validation

schema = {"name": str, "age": int}
valid = all(isinstance(v, schema[k]) for k, v in data.items())

Validate data against a schema.

104.Data Sampling

import random
sample = dict(random.sample(data.items(), 5))

Randomly sample data from a dictionary.

105.Data Chunking

chunks = [dict(list(data.items())[i : i + 10]) for i in range(0, len(data), 10)]

Chunk data into smaller dictionaries.

106.Data Pivoting

pivot = {(x["year"], x["month"]): x["value"] for x in data}

Pivot data into a new structure.

107.Data Aggregation

from collections import defaultdict

totals: defaultdict[str, float] = defaultdict(float)
for record in data:
    totals[record["category"]] += record["amount"]

Aggregate data by category.

108.Data Filtering

filtered = {k: v for k, v in data.items() if v > threshold}

Filter data based on a threshold.

109.Data Normalization

max_val = max(data.values())
normalized = {k: v / max_val for k, v in data.items()}

Normalize data values.

110.Data Merging

merged = {}
for d in dict_list:
    merged.update(d)

Merge multiple dictionaries into one.

111.Data Sorting Output

for k, v in sorted(data.items(), key=lambda kv: -kv[1]):
    print(f"{k}: {v}")

Sort and output data based on values.

112.Data Transformation Pipeline

from functools import reduce

pipeline = [clean_func, transform_func, filter_func]  # type: ignore
result = reduce(lambda d, f: f(d), pipeline, data)

Chain multiple data transformation functions.

113.Data Difference Comparison

diff = {
    k: (dict1[k], dict2[k])
    for k in dict1
    if k in dict2 and dict1[k] != dict2[k]
}

Compare differences between two dictionaries.

114.Data Completion

defaults = {"name": "", "age": 0, "city": "Unknown"}
complete = defaults | user_data

Complete data with default values.

115.Data Masking

sensitive = {"password", "token"}
masked = {k: "*****" if k in sensitive else v for k, v in data.items()}

Mask sensitive data fields.

116.Data Sampling

sample = {k: data[k] for k in random.sample(list(data.keys()), 10)}

Randomly sample data from a dictionary.

117.Data Binning

bins = defaultdict(list)
for k, v in data.items():
    bins[int(v / bin_size)].append(k)

Bin data into categories.

118.Data Expansion

expanded = {f"{k}_{i}": v + i for k, v in data.items() for i in range(3)}

Expand data values into multiple entries.

119.Data Reversal

reversed_dict = dict(reversed(data.items()))

Reverse the order of key-value pairs.

120.Data Pagination

page_size = 10
pages = [dict(list(data.items())[i : i + page_size]) for i in range(0, len(data), page_size)]

Dictionaries are widely used in Python programming, from simple configuration management to complex data analysis, all relying on the support of dictionaries. The 120 operation methods of Python dictionaries cover all aspects from basic creation, access, modification to advanced techniques and practical applications. As one of the most important and efficient data structures in Python, the flexibility and powerful features of dictionaries make them the preferred tool for handling key-value data. By mastering these dictionary operation techniques:

  • Handle and manipulate data more efficiently

  • Write cleaner and more Pythonic code

  • Solve complex data processing problems

  • Improve program performance and readability

  • Efficiently complete various programming tasks

“There is no other secret, just practice!” Use it when needed.If you find this article useful,pleaselike, share, bookmark, comment,and recommend!——Join the Knowledge Community and Learn with More People——

https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c

120 Dictionary Operations in Python

https://ima.qq.com/wiki/?shareId=66042e013e5ccae8371b46359aa45b8714f435cc844ff0903e27a64e050b54b5

120 Dictionary Operations in Python

Leave a Comment