use*_*652 332 python dictionary sequence
I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this?
mar*_*cog 635
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[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
Tau*_*uir 55
如果你想更改所有键:
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}
如果您想更改单个密钥:您可以使用上述任何建议.
kev*_*pie 34
pop'n'fresh
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 
War*_*ard 23
在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() }
Mic*_*ins 11
您可以使用 iff/else 字典理解。此方法允许您替换一行中任意数量的键,并且不需要您更改所有键。
key_map_dict = {'a':'apple','c':'cat'}
d = {'a':1,'b':2,'c':3}
d = {(key_map_dict[k] if k in key_map_dict else k):v  for (k,v) in d.items() }
退货{'apple':1,'b':2,'cat':3}
小智 8
d = {1:2,3:4}
假设我们要更改列表元素 p=['a' , 'b'] 的键。以下代码将执行以下操作:
d=dict(zip(p,list(d.values()))) 
我们得到
{'a': 2, 'b': 4}
由于键是字典用于查找值的键,因此无法真正更改它们.您可以做的最接近的事情是保存与旧密钥关联的值,删除它,然后使用替换密钥和保存的值添加新条目.其他几个答案说明了可以实现的不同方法.
没有直接的方法可以做到这一点,但您可以先删除再分配
d = {1:2,3:4}
d[newKey] = d[1]
del d[1]
或进行批量密钥更改:
d = dict((changeKey(k), v) for k, v in d.items())
小智 5
如果您有复杂的字典,则表示该字典中有一个字典或列表:
myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict
Output
{1: 'one', 2: {3: 'three', 5: 'four'}}
小智 5
转换字典中的所有键
假设这是你的字典:
>>> sample = {'person-id': '3', 'person-name': 'Bob'}
要将示例字典键中的所有破折号转换为下划线:
>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}
此函数获取一个 dict 和另一个指定如何重命名键的 dict;它返回一个新的字典,带有重命名的键:
def rekey(inp_dict, keys_replace):
    return {keys_replace.get(k, k): v for k, v in inp_dict.items()}
测试:
def test_rekey():
    assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}
| 归档时间: | 
 | 
| 查看次数: | 287238 次 | 
| 最近记录: |