如何更改Python字典中条目的键?
当前回答
我只是要帮我妻子做一些python类的事情,所以我写了这段代码来告诉她如何做。正如标题所示,它只替换键名。这是非常罕见的,你必须替换一个键名,并保持字典的顺序完整,但我还是想分享,因为这篇文章是当你搜索它时谷歌返回的,即使它是一个非常老的线程。
代码:
dictionary = {
"cat": "meow",
"dog": "woof",
"cow": "ding ding ding",
"goat": "beh"
}
def countKeys(dictionary):
num = 0
for key, value in dictionary.items():
num += 1
return num
def keyPosition(dictionary, search):
num = 0
for key, value in dictionary.items():
if key == search:
return num
num += 1
def replaceKey(dictionary, position, newKey):
num = 0
updatedDictionary = {}
for key, value in dictionary.items():
if num == position:
updatedDictionary.update({newKey: value})
else:
updatedDictionary.update({key: value})
num += 1
return updatedDictionary
for x in dictionary:
print("A", x, "goes", dictionary[x])
numKeys = countKeys(dictionary)
print("There are", numKeys, "animals in this list.\n")
print("Woops, that's not what a cow says...")
keyPos = keyPosition(dictionary, "cow")
print("Cow is in the", keyPos, "position, lets put a fox there instead...\n")
dictionary = replaceKey(dictionary, keyPos, "fox")
for x in dictionary:
print("A", x, "goes", dictionary[x])
输出:
A cat goes meow
A dog goes woof
A cow goes ding ding ding
A goat goes beh
There are 4 animals in this list.
Woops, that's not what a cow says...
Cow is in the 2 position, lets put a fox there instead...
A cat goes meow
A dog goes woof
A fox goes ding ding ding
A goat goes beh
其他回答
在python 2.7及更高版本中,您可以使用字典理解: 这是我在使用DictReader读取CSV时遇到的一个例子。用户已经在所有列名后面加上了':'
ori_dict ={“key1:”:1、“key2:”:2,“key3:”:3}
在键中去掉后面的':':
Corrected_dict = {k.replace(':', "): v for k, v in ori_dict.items()}
完整解决方案的示例
声明一个json文件,其中包含你想要的映射
{
"old_key_name": "new_key_name",
"old_key_name_2": "new_key_name_2",
}
加载它
with open("<filepath>") as json_file:
format_dict = json.load(json_file)
创建此函数来使用映射格式化字典
def format_output(dict_to_format,format_dict):
for row in dict_to_format:
if row in format_dict.keys() and row != format_dict[row]:
dict_to_format[format_dict[row]] = dict_to_format.pop(row)
return dict_to_format
方法,如果有人想替换多级字典中出现的所有键。
函数检查字典是否有特定的键,然后遍历子字典并递归调用该函数:
def update_keys(old_key,new_key,d):
if isinstance(d,dict):
if old_key in d:
d[new_key] = d[old_key]
del d[old_key]
for key in d:
updateKey(old_key,new_key,d[key])
update_keys('old','new',dictionary)
因为键是字典用来查找值的,所以实际上不能更改它们。您可以做的最接近的事情是保存与旧键相关联的值,删除它,然后使用替换键和保存的值添加一个新条目。其他几个答案说明了实现这一目标的不同方式。
d = {1:2,3:4}
假设我们想要改变列表元素p=['a', 'b']的键值。 下面的代码可以做到:
d=dict(zip(p,list(d.values())))
我们得到
{'a': 2, 'b': 4}
推荐文章
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构