如何更改Python字典中条目的键?
当前回答
对于熊猫,你可以有这样的东西,
from pandas import DataFrame
df = DataFrame([{"fruit":"apple", "colour":"red"}])
df.rename(columns = {'fruit':'fruit_name'}, inplace = True)
df.to_dict('records')[0]
>>> {'fruit_name': 'apple', 'colour': 'red'}
其他回答
只需2步即可轻松完成:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
或者一步:
dictionary[new_key] = dictionary.pop(old_key)
如果字典[old_key]未定义,将引发KeyError。注意,这将删除字典[old_key]。
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
您可以将相同的值与许多键相关联,或者只是删除一个键并重新添加具有相同值的新键。
例如,如果你有键->值:
red->1
blue->2
green->4
没有理由不能添加紫色->2或删除红色->1并添加橙色->1
这将小写你所有的字典键。即使你有嵌套的字典或列表。您可以执行类似的操作来应用其他转换。
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 2.7及更高版本中,您可以使用字典理解: 这是我在使用DictReader读取CSV时遇到的一个例子。用户已经在所有列名后面加上了':'
ori_dict ={“key1:”:1、“key2:”:2,“key3:”:3}
在键中去掉后面的':':
Corrected_dict = {k.replace(':', "): v for k, v in ori_dict.items()}
注意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))
推荐文章
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构