如何更改Python字典中条目的键?
当前回答
在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()}
其他回答
我只是要帮我妻子做一些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
注意pop的位置: 将你想要删除的键放在pop()之后 orig_dict['AAAAA'] = orig_dict.pop('A')
orig_dict = {'A': 1, 'B' : 5, 'C' : 10, 'D' : 15}
# printing initial
print ("original: ", orig_dict)
# changing keys of dictionary
orig_dict['AAAAA'] = orig_dict.pop('A')
# printing final result
print ("Changed: ", str(orig_dict))
d = {1:2,3:4}
假设我们想要改变列表元素p=['a', 'b']的键值。 下面的代码可以做到:
d=dict(zip(p,list(d.values())))
我们得到
{'a': 2, 'b': 4}
因为键是字典用来查找值的,所以实际上不能更改它们。您可以做的最接近的事情是保存与旧键相关联的值,删除它,然后使用替换键和保存的值添加一个新条目。其他几个答案说明了实现这一目标的不同方式。
如果你想更改所有的键:
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
如果你想改变单键: 你可以选择上面的任何一个建议。
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 不区分大小写的字符串作为HashMap键
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- 使用linq转换列表到字典,不用担心重复
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本