简体   繁体   中英

update dict value from one to another based on condition python

Is there any better way to write following code? I have two dict with same set of data as key, I want to iterate dict_a and check if any key with only one value, then update the value to dict_b. I have following working code but it seem there should be a better way to do it

dict_a = {
'first': {1,2},
'second': {2, 7, 10, 22},
'third': {3},
'fourth': {6,8},
'fifth': {1},
}
dict_b = {
'first': 11,
'second': 4,
'third': 1,
'fourth': 1000,
'fifth': 8
}
for k, v in dict_a.items():
    if len(v) == 1:
        dict_b[k] = v.pop()
#=>  
#dict_b = {
#'first': 11,
#'second': 4,
#'third': 3,
#'fourth': 1000,
#'fifth': 1
#}

You are, possibly unnecessarily, modifying dict_a when you use pop on set values in dict_a . You can, instead, use next + iter to extract the only value of a set :

dict_b[k] = next(iter(v))

You can make it a one-liner using update and a generator:

dict_b.update((k, v.pop()) for k, v in dict_a.items() if len(v) == 1)

Algorithmically, this doesn't gain anything, but will utilize some optimzations that come with the used syntactic means.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM