My dictionary has tuples as keys, and the tuples have only one element each. For each key in the dictionary I need to convert it to the string value inside the tuple.
I have tried the following code: I used key[0] because every key is a tuple of length 1.
for key in dictionary:
dictionary[key[0]] = dictionary.pop(key)
dictionary
The code above gives the following error: RuntimeError: dictionary changed size during itera
You can copy your dictionary over like so:
dict_copy = {key[0]: value for key, value in dictionary.items()}
This is a dictionary comprehension, equivalent to doing
dict_copy = dict() # or {}
for key, value in dictionary.items():
dict_copy[key[0]] = dictionary[key]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.