Is it possible to assign the same value to multiple keys in a dict object at once?

前端 未结 6 1899
时光取名叫无心
时光取名叫无心 2020-11-27 03:44

In Python, I need a dictionary object which looks like:

{\'a\': 10, \'b\': 20, \'c\': 10, \'d\': 10, \'e\': 20}

I\'ve been able to get th

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 04:01

    Your first example can be simplified using a loop:

    myDict = {}
    for key in ['a', 'c', 'd']:
        myDict[key] = 10
    for key in ['b', 'e']:
        myDict[key] = 20
    

    No specialized syntax or trickery, and I can't think of anything which would be easier to understand.

    Regarding your second question, there is no simple and efficient way to do the lookup as in your second example. I can only think of iterating over the keys (tuples) and checking whether the key is in any of them, which isn't what you're looking for. Stick to using a straightforward dict with the keys you want.

    In general, if you are aiming for code that can be understood by novices, stick to the basics such as if conditions and for/while loops.

提交回复
热议问题