Original keys (dict_keys with tuple as keys) are:
JavaScript
x
2
1
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')])
2
How can I turn them to:
JavaScript
1
2
1
dict_keys(['00a1', '0q00', '0b0q', '0cc0', '0e00'])
2
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.
Advertisement
Answer
You can use dictionary comprehension to create new dict with new keys:
JavaScript
1
16
16
1
old_dict = {
2
(0.8, 1.6, '00a1'):'some_value',
3
(0.8, 1.6, '0q00'):'some_value',
4
(0.8, 1.6, '0b0q'):'some_value',
5
(0.8, 1.6, '0cc0'):'some_value',
6
(0.8, 1.6, '0e00'):'some_value',
7
}
8
9
print('Old dictionary keys: ', end='')
10
print(old_dict.keys())
11
12
new_dict = {k[2]: v for k, v in old_dict.items()}
13
14
print('New dictionary keys: ', end='')
15
print(new_dict.keys())
16
Prints:
JavaScript
1
3
1
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')])
2
New dictionary keys: dict_keys(['00a1', '0q00', '0b0q', '0cc0', '0e00'])
3