Python Dictionary Comprehension

前端 未结 8 1271
Happy的楠姐
Happy的楠姐 2020-11-21 13:10

Is it possible to create a dictionary comprehension in Python (for the keys)?

Without list comprehensions, you can use something like this:

l = []
fo         


        
8条回答
  •  有刺的猬
    2020-11-21 13:46

    I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.

    keys = ['a', 'b', 'c']
    values = [1, 2, 3]
    d = dict(zip(keys, values))
    

    giving

    d = {'a': 1, 'b': 2, 'c': 3}

提交回复
热议问题