Filter a dict of dict

前端 未结 4 1154
不思量自难忘°
不思量自难忘° 2020-12-19 16:01

I new in Python and I am not sure it is a good idea to use dict of dict but here is my question. I have a dict of dict and I want to filter by the key of the inside dict:

4条回答
  •  爱一瞬间的悲伤
    2020-12-19 16:41

    Try this:

    >>> { k: v['id1'] for k,v in a.items() if 'id1' in v }
    {'key3': [4, 5, 6], 'key1': [0, 1, 2]}
    

    For Python 2.x you might prefer to use iteritems() instead of items() and you'll still need a pretty recent python (2.7 I think) for a dictionary comprehension: for older pythons use:

    dict((k, v['id1']) for k,v in a.iteritems() if 'id1' in v )
    

    If you want to extract multiple values then I think you are best to just write the loops out in full:

    def query(data, wanted):
        result = {}
        for k, v in data.items():
            v2 = { k2:v[k2] for k2 in wanted if k2 in v }
            if v2:
                result[k] = v2
        return result
    

    giving:

    >>> query(a, ('id1', 'id2'))
    {'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
    

提交回复
热议问题