How to turn the following dictionary keys to another keys?

Tags:



Original keys (dict_keys with tuple as keys) are:

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.

Answer

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'])


Source: stackoverflow