Home > database >  Iterating through a List of dictionaries in python
Iterating through a List of dictionaries in python

Time:10-21

I have a list and in that list there are multiple records of dictionaries. I want to create a new list with some of the dictionaries in my previous list.

for example,

s_dict = [{'cs':'10', 'ca':'11', 'cb':'12', 'cc':'same'}, {'cs':'114', 'ca':'121','cb':'132', 'cc':'diff'}, {'cs':'20', 'ca':'21', 'cb':'22', 'cc':'same'}, {'cs':'210', 'ca':'211', 'cb':'212', 'cc':'diff'}]

In the above dictionary I want to make a new list below which will only contain the dictionary where the key 'cc' == 'same' hence the new list will only contain 2 dictionaries from the 4 that where stated above.

Is there a way of doing this?

for val in s_dict:
    for key in val:
        print(val[key])
print(type(s_dict))

index = 0
while index < len(s_dict):
    for key in s_dict[index]:
        print(s_dict[index][key])
    index  = 1

for dic in s_dict:
    for val,cal in dic.items():
        if cal == 'same':
            print(f'{val} is {cal}')
        else:
            print('nothing')

The Above are the ways I've tried doing it but then it gives me back either the keys alone or the values on their own. I want it to return a complete list but only with specific dictionaries containing a key thats equal to a specific value.

CodePudding user response:

new = [i for i in s_dict if ('cc','same') in i.items()]

CodePudding user response:

In your code you can change

res = []
for dic in s_dict:
    for val,cal in dic.items():
        if cal == 'same':
            res.append(dic)
print(res)
# [{'cs': '10', 'ca': '11', 'cb': '12', 'cc': 'same'}, {'cs': '20', 'ca': '21', 'cb': '22', 'cc': 'same'}]
  • Related