Home > database >  get dict based on key value dynamically
get dict based on key value dynamically

Time:04-05

I changed the question completely to make the concept easier.

I have a listed dictionary and I want to print out dictionaries that have the same id key value.

Here is a listed dictionary:

testdata = [{"id": "test1",
            "data":"book",
            "type":"work"},
            {"id": "test2",
            "data":"cd",
            "type":"school"},
            {"id": "test1",
            "data":"cd",
            "type":"school"},
            {"id": "test3",
            "data":"book",
            "type":"work"}]

Example question - how can I print just the dictionaries that have test1 as the value for the id key?

I can do this statically by saying:

for r in testdata:
    if r["id"] == "test1":
        print(r)

but how can I print the same thing if I didn't know the id's name before hand. how can I dynamically look for key values that have the same id and print them in a forloop or append to a new list?

CodePudding user response:

ids = set((d['id'] for d in testdata))

for id_ in ids:
  print ([data for data in testdata if data['id'] == id_])

#Output:
[{'id': 'test2', 'data': 'cd', 'type': 'school'}]
[{'id': 'test3', 'data': 'book', 'type': 'work'}]
[{'id': 'test1', 'data': 'book', 'type': 'work'}, {'id': 'test1', 'data': 'cd', 'type': 'school'}]

sort and groupby will also do

from itertools import groupby

# create a func that gives the key to sort and group.
key_func = lambda d: d['id']

# First, Sort the list based on the needed field. 
sorted_test_data = sorted(testdata, key=key_func)

# Next, simply group them by the field. 
for key, group in groupby(sorted_test_data, key_func):
  print(key   " :", list(group))
  • Related