Home > database >  How can you filter a list of dictionary in python with list as value
How can you filter a list of dictionary in python with list as value

Time:01-26

#List of dictionary

List_of_dict = [
    {'id': 1,'Name':Tom, 'Data':[10,20,30,40,50],'Value':[1,2,3,4,5] },
    {'id': 2,'Name':Jack, 'Data':[10,20,30,],'Value':[3,4] },
    {'id': 3,'Name':Nancy, 'Data':[10,20],'Value':[3,4,5] },
    {'id': 4,'Name':Jack, 'Data':[20,],'Value':[1]}
]

Quest : Want to create a filter for data 30 and value 3 Expected - 1:

Output_dict = [{'id': 1,'Name':Tom, 'Data':[10,20,30,40,50],'Value':[1,2,3,4,5] },{'id': 2,'Name':Jack, 'Data':[10,20,30,],'Value':[3,4]

used this >>

Output_dict = [out for out in List_of_dict if  out['Data'] == [30] and out['Value'] == [3] ]

I don't get desired output with above

Also how do I create filter for Data: 20' and Value:3 or 4 Expected - 2:

[{'id': 1,'Name':Tom, 'Data':[10,20,30,40,50],'Value':[1,2,3,4,5] },{'id': 2,'Name':Jack, 'Data':[10,20,30,],'Value':[3,4] },{'id': 3,'Name':Nancy, 'Data':[10,20],'Value':[3,4,5] }]

CodePudding user response:

You are testing against lists that have no match in your data.

Use e.g.

Output_dict = [out for out in List_of_dict if  30 in out['Data'] and 3 in out['Value']]

CodePudding user response:

The problem with your code is that it's searching for an exact match: out['Data'] == [30]. You need to use in instead like 30 in out['Data'].

So it could be changed to:

out1 = [d for d in List_of_dict if (30 in d.get('Data', [])) and (3 in d.get('Value', []))]

Output:

[{'id': 1,
  'Name': 'Tom',
  'Data': [10, 20, 30, 40, 50],
  'Value': [1, 2, 3, 4, 5]},
 {'id': 2, 'Name': 'Jack', 'Data': [10, 20, 30], 'Value': [3, 4]}]

For the second case, you can use set.intersection to check if 3 or 4 exist in any d['Value']:

out2 = [d for d in List_of_dict if (20 in d.get('Data', [])) and (set(d.get('Value', [])) & {3, 4})]

Output:

[{'id': 1,
  'Name': 'Tom',
  'Data': [10, 20, 30, 40, 50],
  'Value': [1, 2, 3, 4, 5]},
 {'id': 2, 'Name': 'Jack', 'Data': [10, 20, 30], 'Value': [3, 4]},
 {'id': 3, 'Name': 'Nancy', 'Data': [10, 20], 'Value': [3, 4, 5]}]
  •  Tags:  
  • Related