I have a python dictionary.
project = {
5:{"name:Mark"},
1:{"name:Mark"},
3:{"name:Mark"},
4:{"name:Kim"},
2:{"name:Kim"},
}
I want to reset the keys.
project = {
1:{"name:Mark"},
2:{"name:Mark"},
3:{"name:Mark"},
4:{"name:Kim"},
5:{"name:Kim"},
}
How could I do that?
Yes, now that python has an ordered dict
the key value pairs keep their order when you iterate over them. You just have to give the values new keys:
project = {
5:{"name:Mark"},
1:{"name:Mark"},
3:{"name:Mark"},
4:{"name:Kim"},
2:{"name:Kim"},
}
project = {index:value for index,value in enumerate(project.values(), 1)}
print(project)
Output as requested.
(Note the short version given in the comment below:)
project = dict(enumerate(project.values(), 1))
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.