Filter a dict of dict

前端 未结 4 1126
不思量自难忘°
不思量自难忘° 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:38

    According to the precision you gave to Duncan, here is another filtering on a list using dictionary comprehension:

    >>> my_list = ['id1', 'id2']
    >>> {k1 : {k2: v2 for (k2, v2) in a[k1].iteritems() if k2 in my_list} for k1 in a}
    {'key3': {'id1': [4, 5, 6]}, 'key2': {}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
    

    EDIT: you can also remove empty values with another dict compreehension, but that "begins" to be difficult to read... :-)

    >>> {k3: v3 for k3, v3 in {k1 : {k2: v2 for (k2, v2) in a[k1].iteritems() if k2 in my_list} for k1 in a}.iteritems() if v3}
    {'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
    

提交回复
热议问题