Python-在字典的指定位置添加键值对

from collections import OrderedDict

# 方式一
def modify_dict_1(source_dict, new_key, old_key, value):
    """
    将dict初始化为OrderedDict。创建一个新的空OrderedDict,遍历原始字典的所有键,并在键名匹配时插入before/after
    """
    new_dict = OrderedDict()
    for k, v in source_dict.items():
        if k == old_key:
            new_dict[new_key] = value
        new_dict[k] = v
    return dict(new_dict)


old_dict = OrderedDict([('name', 'li'), ('age', 26), ('cls', 'one')])
print(modify_dict_2(old_dict, "address", "age", "china"))  # {'name': 'li', 'address': 'china', 'age': 26, 'cls': 'one'}

# 方式二
def modify_dict_2():
    """
    使用列表存储键,使用dict存储值的方式
    """
    my_keys = ['key_1', 'key_2', 'key_3']
    source_dict = {'key_1': 'li', 'key_2': "wg", 'key_3': 'zh'}
    k, v = 'key_4', 'hello'
    my_keys.insert(my_keys.index('key_1') + 1, k)
    source_dict[k] = v
    new_dict = {}
    for k in my_keys:
        new_dict.update({k: source_dict[k]})
    print(new_dict)  # {'key_1': 'li', 'key_4': 'hello', 'key_2': 'wg', 'key_3': 'zh'}

你可能感兴趣的:(Python-杂谈)