Python dictionary iteration

前端 未结 2 594
情话喂你
情话喂你 2021-02-07 02:41

I have a dictionary dict2 which I want to iter through and remove all entries that contain certain ID numbers in idlist. dict2[x] is a li

相关标签:
2条回答
  • 2021-02-07 03:08

    An approach using sets (Note that I needed to change your variables A, B, C, etc. to strings and the numbers in your idlist to actual integers; also this only works, if your IDs are unique and don't occur in other 'fields'):

    #!/usr/bin/env python
    # 2.6 <= python version < 3
    
    original = {
        'G1' : [
            ['A', 123456, 'C', 'D'], 
            ['A', 654321, 'C', 'D'], 
            ['A', 456123, 'C', 'D'], 
            ['A', 321654, 'C', 'D'],
        ]
    }
    
    idlist = [123456, 456123, 321654]
    idset = set(idlist)
    
    filtered = dict()
    
    for key, value in original.items():
        for quad in value:
            # decide membership on whether intersection is empty or not
            if not set(quad) & idset:
                try:
                    filtered[key].append(quad)
                except KeyError:
                    filtered[key] = quad
    
    print filtered
    # would print:
    # {'G1': ['A', 654321, 'C', 'D']}
    
    0 讨论(0)
  • 2021-02-07 03:29

    Try a cleaner version perhaps?

    for k in dict2.keys():
        dict2[k] = [x for x in dict2[k] if x[1] not in idlist]
        if not dict2[k]:
            del dict2[k]
    
    0 讨论(0)
提交回复
热议问题