如何更改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()}
其他回答
流行与新鲜
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>
d = {1:2,3:4}
假设我们想要改变列表元素p=['a', 'b']的键值。 下面的代码可以做到:
d=dict(zip(p,list(d.values())))
我们得到
{'a': 2, 'b': 4}
我还没有看到确切的答案:
dict['key'] = value
您甚至可以对对象属性执行此操作。 通过这样做,将它们编入字典:
dict = vars(obj)
然后你可以像操作字典一样操作对象属性:
dict['attribute'] = value
这将小写你所有的字典键。即使你有嵌套的字典或列表。您可以执行类似的操作来应用其他转换。
def lowercase_keys(obj):
if isinstance(obj, dict):
obj = {key.lower(): value for key, value in obj.items()}
for key, value in obj.items():
if isinstance(value, list):
for idx, item in enumerate(value):
value[idx] = lowercase_keys(item)
obj[key] = lowercase_keys(value)
return obj
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}
lowercase_keys(json_str)
Out[0]: {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
'emb_dict': {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}
我只是要帮我妻子做一些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
推荐文章
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构