简体   繁体   English

Python 3 按特定键值过滤有序dict项的列表

[英]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".我正在尝试过滤新的有序 dict 条目以仅获得列表中变量 8 等于“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')?如何解决此问题以仅检索 var8 等于特定值('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.结果应该是有序 dict 对象的列表,其中 var8 等于“C”,而不管其他变量等于什么。 Other potential values for var8 could be blank or none. var8 的其他潜在值可能为空白或无。

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.您的问题是, for a, b in orglist不起作用,因为遍历字典只会为您提供字典键。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM