Search code examples
pythonpython-3.xordereddictionary

Python 3 filter list of ordered dict items by a specific key value


I am iterating a list of other list variables to an ordered dictionary variable and appending them to a new list variable. I am trying to filter the new ordered dict entries to only get the results where variable 8 in the list is equal to "C". The code I have below is giving me a value error though.

    keys = ['key1', 'key2', 'key3', 'key4', 'key5', 'key6', 'key7', 'key8']
    blank_list = []
    for a in list(zip(var1, var2, var3, var4, var5, var6, var7, var8):
        orglist = OrderedDict(zip(keys, a))
        orglist2 = {a: b for a, b in orglist if b[8] == 'C'}
        blank_list.append(orglist2)

How can I fix this to only retrieve ordereddict values where var8 is equal to a specific value ('C')? The result should be a list of ordered dict objects where the var8 is equal to 'C' regardless of what the other variables equal. Other potential values for var8 could be blank or none.


Solution

  • If you want to keep your approach, this should fix it:

    keys = ['key1', 'key2', 'key3', 'key4', 'key5', 'key6', 'key7', 'key8']
    blank_list = []
    for a in zip(var1, var2, var3, var4, var5, var6, var7, var8):
        orglist = OrderedDict(zip(keys, a))
        orglist2 = {a: b for a, b in orglist.items() if b[6] == 'C'}
        blank_list.append(orglist2)
    

    Your issue was, that for a, b in orglist wouldn't work, because iterating through a dictionary only gives you the dictionary keys.

    but maybe this would be bit more readable:

    for a in zip(var1, var2, var3, var4, var5, var6, var7, var8):
        if a[6] == 'C':
            blank_list.append(dict(zip(keys, a)))
    

    or

    for a in zip(var1, var2, var3, var4, var5, var6, var7, var8):
        orglist = OrderedDict(zip(keys, a))
        if orglist['key7'] == 'C':
            blank_list.append(orglist)