Python Dictionary Comprehension

前端 未结 8 1273
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:09

    Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length

    i_s = range(1, 11)
    x_s = range(1, 11)
    # x_s = range(11, 1, -1) # Also works
    d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])
    
    0 讨论(0)
  • 2020-11-21 14:11

    The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.

    Instead of writing

    l = []
    for n in range(1, 11):
        l.append(n)
    

    or

    l = [n for n in range(1, 11)]
    

    you should write only

    l = range(1, 11)
    

    In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.

    To get a new dictionary with all keys set to the same value based on another dict, do this:

    old_dict = {'a': 1, 'c': 3, 'b': 2}
    new_dict = { key:'your value here' for key in old_dict.keys()}
    

    You're receiving a SyntaxError because when you write

    d = {}
    d[i for i in range(1, 11)] = True
    

    you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like

    d[[i for i in range(1, 11)]] = True
    

    and not

    d[i for i in range(1, 11)] = True
    

    but lists are not hashable, so you can't use them as dict keys.

    0 讨论(0)
提交回复
热议问题