Amit
Amit

Reputation: 11

Python: Search in an array of dictionaries by a given key

I have an array of dictionaries d which I obtain by parsing a JSON file: d = r.json()

Assuming d then contains

d = [
  {'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
  {'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
  {'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
  {'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'},
]

where all the hostnames are different from each other, how can I then perform a search like

if hostname=='a1':
  print change (i.e 182)

Upvotes: 0

Views: 44

Answers (3)

CristiC777
CristiC777

Reputation: 481

First of all you have a lot of json structure errors:

d=[{'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
{'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
{'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
{'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'}]


 hostname='a1'
 for row in d:
   arr = row['hostname'].split(",")
   if hostname in arr:
     print(row['change'])




 #parse all the keys for learning.
  for row in d:
     for k in row.keys():
         if k == "hostname":
             arr = row[k].split(",")
             for s in arr:
                 #print(s)
                 if s =='a1':
                     row['change'] = '777'

print(d)

after that use reverse to re-arrange the tuples in json. Have fun !

Upvotes: 0

Jared Wilber
Jared Wilber

Reputation: 6805

The Pythonic way of solving this (using a comprehension) is also the easiest.

# for your a1 example
change_a1 = [i['change'] for i in d
             if 'a1' in i['hostname']]

For an arbitrary search, just wrap it as a function

def find_change(host):
    change = [i['change'] for i in d
              if host in i['hostname']]
    return change

Upvotes: 0

Daniel F
Daniel F

Reputation: 14239

You need to iterate over the list, split the hostnames into a list and check if the hostname you are searching for exists in that list.

hostname = 'a1'
for row in d:
  hostnames = row['hostname'].split(',')
  if hostname in hostnames:
    print(row['change'])

Upvotes: 1

Related Questions