Python list comprehension for dictionaries in dictionaries?

后端 未结 5 2131
借酒劲吻你
借酒劲吻你 2021-01-03 19:46

I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something\'s bugging me.

In my test I have this kind of

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 20:39

    If dct is

    {'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
     'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}
    

    Perhaps you are looking for something like:

    [ subdct for key,subdct in dct.iteritems() 
      if 92

    A little nicety is that Python allows you to chain inequalities:

    92

    instead of

    if r['x'] > 92 and r['x'] < 95
    

    Note also that above I've written a list comprehension, so you get back a list (in this case, of dicts).

    In Python3 there are such things as dict comprehensions as well:

    { n: n*n for n in range(5) } # dict comprehension
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

    In Python2 the equivalent would be

    dict( (n,n*n) for n in range(5) )
    

    I'm not sure if you are looking for a list of dicts or a dict of dicts, but if you understand the examples above, it is easy to modify my answer to get what you want.

提交回复
热议问题