Python Dictionary Comprehension

前端 未结 8 1312
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:45

    you can't hash a list like that. try this instead, it uses tuples

    d[tuple([i for i in range(1,11)])] = True
    
    0 讨论(0)
  • 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}

    0 讨论(0)
  • 2020-11-21 13:52

    You can use the dict.fromkeys class method ...

    >>> dict.fromkeys(range(5), True)
    {0: True, 1: True, 2: True, 3: True, 4: True}
    

    This is the fastest way to create a dictionary where all the keys map to the same value.

    But do not use this with mutable objects:

    d = dict.fromkeys(range(5), [])
    # {0: [], 1: [], 2: [], 3: [], 4: []}
    d[1].append(2)
    # {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
    

    If you don't actually need to initialize all the keys, a defaultdict might be useful as well:

    from collections import defaultdict
    d = defaultdict(True)
    

    To answer the second part, a dict-comprehension is just what you need:

    {k: k for k in range(10)}
    

    You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:

    >>> class KeyDict(dict):
    ...    def __missing__(self, key):
    ...       #self[key] = key  # Maybe add this also?
    ...       return key
    ... 
    >>> d = KeyDict()
    >>> d[1]
    1
    >>> d[2]
    2
    >>> d[3]
    3
    >>> print(d)
    {}
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-11-21 14:04
    >>> {i:i for i in range(1, 11)}
    {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
    
    0 讨论(0)
  • 2020-11-21 14:05

    There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.

    >>> d = {n: n**2 for n in range(5)}
    >>> print d
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

    If you want to set them all to True:

    >>> d = {n: True for n in range(5)}
    >>> print d
    {0: True, 1: True, 2: True, 3: True, 4: True}
    

    What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

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