2021年3月3日星期三

Is there any way to iterate and slice keys of a dictionary in python

I've been trying to wrap my head over this for the past six hours or so but I've been trying to iterate and slice all keys in a dictionary whilst preserving the values and transfer all items to a new dictionary.

new_dictionary={}  current_dictionary={"XXXX1234":43,"XXXX4547":58, "YYYY4948":93,"YYYY5050":45}   for key,value in current_dictionary.items():    if current_dictionary not in new_dictionary:      new_dictionary.update({key[0:4]:value})  print(new_dictionary)  

The result should be

{"XXXX":43,"XXXX":58, "YYYY":93,"YYYY":45}  

Instead, I get this.

{"XXXX":58,"YYYY":45}   

I don't want to try and convert it into a list and slice it there but I want to find a direct way and I've been scrambling my brains over this for the past afternoon.

https://stackoverflow.com/questions/66467977/is-there-any-way-to-iterate-and-slice-keys-of-a-dictionary-in-python March 04, 2021 at 11:04AM

没有评论:

发表评论