Creating a list with specific values from a list of dictionaries (keys as strings and values are list of integers)

Viewed 63

I have a list of dictionaries with a string and a list of strings as values for their respective keys:

list_of_dictionaries = [
    {'id': 'ABBA', 'num': ['10', '3', '5', '1']},
    {'id': 'ABAC', 'num': ['4', '5', '6', '20']}]

Each letter in the 'id' string corresponds with the number in 'num' at matching indices. So for value 'ABBA' it would match the value in 'num' at each position in order: A = 10, B = 3, B = 5, A = 1. I would like return a list of the ids with 'num' > 5 in each dictionary while maintaining their current order.

Here is my attempt:

bad_values = ['','0','1','2','3','4','5']
final_ids =[]
for i in list_of_dictionaries:
     list_of_high_num =[]
     for id,num in enumerate(i.items()):
          if i["num"] is not bad_values:
             list_of_high_num.append(i["id"])
        final_ids.append(list_of_high_num)

However, I'm just getting my original string of ids back in a list. Where am I going wrong?

Desired output something like this:

final_list = [['A'], ['A', 'C']]
1 Answers

considering the scenario for each dictionary item len(id) = len(num)

list_of_dictionaries = [
    {'id': 'ABBA', 'num': ['10', '3', '5', '1']},
    {'id': 'ABAC', 'num': ['4', '5', '6', '20']}]

limit = 5

outerlist = []
for d in list_of_dictionaries:
    innerlist = []
    for x in range(len(d['num'])):
        if int(d['num'][x]) > limit:
            innerlist.append(d['id'][x])
    outerlist.append(innerlist)

print(outerlist) # [['A'], ['A', 'C']]
Related