How to exchange dictionary key values in Python

How to exchange dictionary key values ​​in Python

1. Use dictionary derivation

1. Create a new dictionary and exchange the keys and values ​​based on the original dictionary. The code is as follows:

# 创建原始字典
original_dict = {
    
    'a': 1, 'b': 2, 'c': 3}

# 使用字典推导式互换键值
inverted_dict = {
    
    value: key for key, value in original_dict.items()}

print(inverted_dict)

# 输出结果:{1: 'a', 2: 'b', 3: 'c'}

2. Using dictionary derivation, you can realize key-value exchange in the dictionary with one line of code. This method is suitable for the case where the keys and values ​​of the original dictionary are unique.

2. Use zip function to decompress

1. Use the zip function and decompression method to realize key-value exchange in the dictionary. The code is as follows:

# 创建原始字典
original_dict = {
    
    'a': 1, 'b': 2, 'c': 3}

# 使用zip函数和解压实现键值互换
inverted_dict = dict(zip(original_dict.values(), original_dict.keys()))

print(inverted_dict)

# 输出结果:{1: 'a', 2: 'b', 3: 'c'}

2. Use the zip function to combine the values ​​and keys of the original dictionary into tuples, and then decompress and assign the values ​​to the new dictionary to achieve key-value exchange.

3. Implementation using loop traversal

1. Use a loop to traverse the original dictionary and exchange the positions of keys and values ​​one by one to achieve key-value exchange in the dictionary. The code is as follows:

# 创建原始字典
original_dict = {
    
    'a': 1, 'b': 2, 'c': 3}

# 使用循环遍历实现键值互换
inverted_dict = {
    
    }
for key, value in original_dict.items():
    inverted_dict[value] = key

print(inverted_dict)

# 输出结果:{1: 'a', 2: 'b', 3: 'c'}

2. Use loop traversal to exchange the positions of keys and values ​​one by one, use the keys in the original dictionary as the values ​​of the new dictionary, and use the values ​​in the original dictionary as the keys of the new dictionary.

4. Precautions

1. When exchanging dictionary key values, you need to ensure that the keys and values ​​of the original dictionary are unique.

2. If there are duplicate values ​​in the original dictionary, only one key can be used as the key of the new dictionary, and the values ​​of other keys will be overwritten.

3. The above method is suitable for dictionary data structures in Python, and there may be different implementations in other data structures.

General catalog of "AUTOSAR lineage decomposition (ETAS tool chain)"

Guess you like

Origin blog.csdn.net/PlutoZuo/article/details/132849186