Nested dictionary comprehension python

前端 未结 3 636
走了就别回头了
走了就别回头了 2020-11-30 02:21

I\'m having trouble understanding nested dictionary comprehensions in Python 3. The result I\'m getting from the example below outputs the correct structure without error,

相关标签:
3条回答
  • 2020-11-30 02:53

    Adding some line-breaks and indentation:

    data = {
        outer_k: {inner_k: myfunc(inner_v)} 
        for outer_k, outer_v in outer_dict.items()
        for inner_k, inner_v in outer_v.items()
    }
    

    ... makes it obvious that you actually have a single, "2-dimensional" dict comprehension. What you actually want is probably:

    data = {
        outer_k: {
            inner_k: myfunc(inner_v)
            for inner_k, inner_v in outer_v.items()
        } 
        for outer_k, outer_v in outer_dict.items()
    }
    

    (which is exactly what Blender suggested in his answer, with added whitespace).

    0 讨论(0)
  • 2020-11-30 02:54
    {ok: {ik: myfunc(iv) for ik, iv in ov.items()} for ok, ov in od.items()}  
    

    where
    ok-outer key
    ik-inner key
    ov-outer value
    iv-inner value od-outer dictionary This is how i remember.

    0 讨论(0)
  • 2020-11-30 03:09

    {inner_k: myfunc(inner_v)} isn't a dictionary comprehension. It's just a dictionary.

    You're probably looking for something like this instead:

    data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}
    

    For the sake of readability, don't nest dictionary comprehensions and list comprehensions too much.

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