0

I want to perform searches on values in a list of nested dictionaries and return another key:value pairs. These dictionaries are metafiles. Basically I want to search the ID of each dictionary, find all dictionaries that have the same ID, and return the file location (key:value) pairs.

metafile = [{'metadata':{'Title':'The Sun Also Rises', 'ID': 'BAY121-F1164EAB499'}, 'content': 'xyz', 'File_Path': 'file_location1'},
{'metadata':{'Title':'Of Mice and Men', 'ID': '499B0BAB@dfg'}, 'content': 'abc', 'File_Path': 'file_location2'},
{'metadata':{'Title':'The Sun Also Rises Review', 'ID': 'BAY121-F1164EAB499'}, 'content': 'ftw', 'File_Path': 'file_location3'}]

I created a loop to perform my search as follows. It returns an empty list though, how should I modify this so that the file paths are returned?

search_ID = 'BAY121-F1164EAB499'
path =[]
for a in metafile:
    for val in a['metadata']['ID']:
        if search_ID == val:
            path.append(a['File_Path'])
byc
  • 121
  • 10
  • Does this answer your question? https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary – Thingamabobs Jun 10 '20 at 15:04

2 Answers2

1

you don't need an inner loop for this:

correct code

search_ID = 'BAY121-F1164EAB499'
path =[]
for a in metafile:
    #a['metadata']['ID'] already gives you the value of ID
    if search_ID == a['metadata']['ID']:
        path.append(a['File_Path'])

output

['file_location1', 'file_location3']
sage07
  • 83
  • 8
  • thanks it works. Testing it on a large amount of dictionaries and it threw me an error `KeyError: 'ID' `. How come? – byc Jun 10 '20 at 15:29
  • because there exists a dictionary with no key "ID" in it inside the list of dictionaries. – sage07 Jun 11 '20 at 03:46
0

You don't need to iterate through a['metadata']['ID'], instead just access them directly. So the modified code would be

    metafile = [{'metadata':{'Title':'The Sun Also Rises', 'ID': 'BAY121- 
    F1164EAB499'}, 'content': 'xyz', 'File_Path': 'file_location1'},
    {'metadata':{'Title':'Of Mice and Men', 'ID': '499B0BAB@dfg'}, 'content': 'abc', 
    'File_Path': 'file_location2'},
    {'metadata':{'Title':'The Sun Also Rises Review', 'ID': 'BAY121-F1164EAB499'}, 
    'content': 'ftw', 'File_Path': 'file_location3'}]

     search_ID = 'BAY121-F1164EAB499'
     path =[]
     for a in metafile:
         if a["metadata"]["ID"] == search_ID:
            path.append(a['File_Path'])
lanxion
  • 1,350
  • 1
  • 7
  • 20