Multiple keys per value

后端 未结 7 1406
抹茶落季
抹茶落季 2020-12-01 11:58

Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key:

dict = {\'k1\':\'v1\', \'k2\':         


        
7条回答
  •  甜味超标
    2020-12-01 12:39

    Using python 2.7/3 you can combine a tuple, value pair with dictionary comprehension.

    keys_values = ( (('k1','k2'), 0), (('k3','k4','k5'), 1) )
    
    d = { key : value for keys, value in keys_values for key in keys }
    

    You can also update the dictionary similarly.

    keys_values = ( (('k1',), int), (('k3','k4','k6'), int) )
    
    d.update({ key : value for keys, value in keys_values for key in keys })
    

    I don't think this really gets to the heart of your question but in light of the title, I think this belongs here.

提交回复
热议问题