[英]How to turn the following dictionary keys to another keys?
Original keys (dict_keys with tuple as keys) are:原始键(以元组为键的 dict_keys)是:
dict_keys([(0.8, 1.6, '00a1'), (0.8, 1.6, '0q00'), (0.8, 1.6, '0b0q'), (0.8, 1.6, '0cc0'), (0.8, 1.6, '0e00')])
How can I turn them to:我怎样才能把它们变成:
dict_keys(['00a1', '0q00', '0b0q', '0cc0', '0e00'])
It is also okay to just create a new dictionary with the new keys.用新键创建一个新字典也是可以的。 But I do not know how to do so either way.但我不知道该怎么做。
You can use dictionary comprehension to create new dict with new keys:您可以使用字典理解来创建具有新键的新字典:
old_dict = {
(0.8, 1.6, '00a1'):'some_value',
(0.8, 1.6, '0q00'):'some_value',
(0.8, 1.6, '0b0q'):'some_value',
(0.8, 1.6, '0cc0'):'some_value',
(0.8, 1.6, '0e00'):'some_value',
}
print('Old dictionary keys: ', end='')
print(old_dict.keys())
new_dict = {k[2]: v for k, v in old_dict.items()}
print('New dictionary keys: ', end='')
print(new_dict.keys())
Prints:印刷:
Old dictionary keys: dict_keys([(0.8, 1.6, '00a1'), (0.8, 1.6, '0q00'), (0.8, 1.6, '0b0q'), (0.8, 1.6, '0cc0'), (0.8, 1.6, '0e00')])
New dictionary keys: dict_keys(['00a1', '0q00', '0b0q', '0cc0', '0e00'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.