Python Dictionary Comprehension

前端 未结 8 1327
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 14:03

    Consider this example of counting the occurrence of words in a list using dictionary comprehension

    my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
    my_dict = {k:my_list.count(k) for k in my_list}
    print(my_dict)
    

    And the result is

    {'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}
    

提交回复
热议问题