0

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Does this answer your question? [How to iterate through a list of dictionaries](https://stackoverflow.com/questions/35864007/how-to-iterate-through-a-list-of-dictionaries) – odaiwa Oct 21 '22 at 07:18

2 Answers2

0
new = [i for i in s_dict if ('cc','same') in i.items()]
Elicon
  • 206
  • 1
  • 11
0

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'}]
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21