Python Dictionary Comprehension

前端 未结 8 1524
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: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)
    {}
    

提交回复
热议问题