Python list comprehension for dictionaries in dictionaries?

后端 未结 5 2129
借酒劲吻你
借酒劲吻你 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:25

    Sounds like you want something like:

    my_dict = {'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
               'test277' : {'y': '072', 'x': '094', 'fname': 'test277'}}
    
    
    new_dict = dict((k,v) for k,v in my_dict.items() 
                        if 92 < int(v['x']) < 95 and 70 < int(v['y']) < 75)
    

    Some notes on this code:

    1. I'm using a generator expression instead of a list comprehension
    2. Python lets you combine inequality tests as low < value < high
    3. The dict() constructor takes an iterable of key/value tuples to create a dictionary

提交回复
热议问题