Python looping through nested arrays - python

I have a json that looks like this:
[
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
I am trying to iterate through the elements array:
for a in json['elements']:
print a['name']
I get this error:
TypeError: list indices must be integers, not str
My python is really bad. Thank you

Try this:
for a in json:
for b in a['elements']:
print b['name']

With your code, you are trying to get the value of the key 'elements' from the dictionary json. But json isn't a dict, but an array of dicts. Thus, what you should do instead is:
for dic_x in json:
for dic_y in dic_x['elements']:
print dic_y['name']

You need to loop through your list and then proceed with your data like what you do with dicts like this example:
my_json = [
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
for element in my_json:
for v in element["elements"]:
print(v["name"])
Output:
foo
bar
foo1
bar1

Related

How can I get the dates from this nested list in Python

My data contains nested lists and I am trying to create a list that contains only the date information from the second layer of nested lists.
"DateMap": {
"2020-12-04:0": {
"55.0": [
{
}]},
"2020-12-11:7": {
"60.0": [
{
}]}
}
I want to get a list that is like this mylist = ["2020-12-04:0", "2020-12-11:7"]
I have looked into using regex and list comprehensions and this is the expression I have found to match the dates ^\d{4}-\d\d-\d\d:\d\d?$
How can I make this work?
Use the function .keys(). This just gets all the keys of a dictionary, which is exactly what you're looking for. If DateMap is inside a dictionary, say dic, just do the same thing for dic["DateMap"].
DateMap = {
"2020-12-04:0": {
"55.0": [
{
}]},
"2020-12-11:7": {
"60.0": [
{
}]}
}
mylist = DateMap.keys()
# mylist = list(DateMap.keys()) for Python 3
print(mylist)
# Prints ['2020-12-04:0', '2020-12-11:7']

How to get values from keys from JSON

I'm trying to get some values from a JSON file in Python to create a curl command with these values from the file.
The values that i am looking for are "alarm-id" and "sequence-id".
The JSON file looks like this:
{
"data": [
{
"attributes": {
"alarm-id": "3672400101833445418",
"sequence-id": "1573135238000"
}
}
]
}
I've tried get() but i cant figure out how to use this correctly.
If you need more information just ask.
Thanks in advance!
Best regards
This should work for you
import json
data = json.loads(#yourJSON)
for attribute in data['data']:
print(attribute['attributes']['alarm-id'])
print(attribute['attributes']['sequence-id'])
You have combination of dictionaries and list. Access dictionary key by name dict["key"] and list element by index.
In short, like this:
>>> d = {"data": [{"attributes":{"alarm-id": "3672400101833445418","sequence-id": "1573135238000"}}]}
>>> d["data"][0]["attributes"]["alarm-id"]
'3672400101833445418'

Python - append JSON into main branch

Maybe I am too stuck to see the simple solution for the following problem:
Given:
import json
a = {
"24631331976_defa3bb61f_k.jpg668058":{
"regions": {
"0": {},
"1": {}
}
}
}
b = {
"16335852991_f55de7958d_k.jpg1767935":{
"regions": {
"0": {}
}
}
}
I want to append them in order to get the following output.
enter image description here
Thanks to Daniel Hepper and SegFault, the problem could be solved with:
a.update(b)
c = {}
c.update(a)
c.update(b)
Alternatively, if you are fine with modifying a:
a.update(b)
Note that your code uses Python dictionaries, not JSON strings.
You cannot 'append' a dict to another one, simply because the append add element to the end of an ordered list of elements.
dicts don't have the notion of order, fist or last element. Thus no append for dict.
The action you want to do is merging two dicts, and you can do that using the update method defined for the dict type.
a.update(b)
PS: that will modify the dict a

How to access the value of 1st key of all the dictionaries saved as a list for a key in JSON using PYTHON

I have the JSON which looks like this:-
{
"name": "PT",
"batservers": [
{"name": "bat1", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat2", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat3", "qmchannel": "abcd", "mount": "efgh"},
]
}
I want to retrieve the value of "name" present in all the dictionary and save it in a list variable i.e. ["bat1","bat2","bat3"]
I tried something like this:-
batsList = env["batservers"][0:]["name"]
but it displays the below error:-
TypeError: list indices must be integers or slices, not str
I know I can do this using a loop but can someone please help me to do using in a single line code way which I am trying above?
Thanks,
SUYASH GUPTA.
You can't do it without a loop. But the loop can be a list comprehension:
batsList = [b['name'] for b in env["batservers"]
How about saving the list as:
list_of_names = [x[name] for x in env["batservers"]]
Try this:
[b['name'] for b in env['batservers']]
Or this:
map(lambda b: b['name'], env['batservers'])
[0:] doesn't do much for you: it returns the same array of dictionaries.
env["batservers"][0:] returns a list, and you can't access directly the values of the dicts in the list.
You can use a list comprehension:
names = [elem["name"] for elem in env["batservers"]]
This is a basic solution using a for loop to iterate over the sub dictionary and appending to the empty list res.
res = []
for item in env["batservers"]:
res.append(item["name"])
print (res) #=> ['bat1', 'bat2', 'bat3']

Getting specific field values from Json Python

I have a JSON file, and what I am trying to do is getting this specific field '_id'. Problem is that when I use json.load('input_file'), it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
because I keep getting this error: TypeError: list indices must be integers or slices, not str
What I also tried to do is:
data = json.load(input_file)[0]
It kinda works. Now, my type is a dictionary, and I can access like this: data['_id']
But I only get the first '_id' from the archive...
So, what I would like to do is add all '_id' 's values into a list, to use later.
input_file = open('input_file.txt')
data = json.load(input_file)[0]
print(data['_id'])# only shows me the first '_id' value
Thanks for the help!
[{
"_id": "5436e3abbae478396759f0cf",
"name": "ISIC_0000000",
"updated": "2015-02-23T02:48:17.495000+00:00"
},
{
"_id": "5436e3acbae478396759f0d1",
"name": "ISIC_0000001",
"updated": "2015-02-23T02:48:27.455000+00:00"
},
{
"_id": "5436e3acbae478396759f0d3",
"name": "ISIC_0000002",
"updated": "2015-02-23T02:48:37.249000+00:00"
},
{
"_id": "5436e3acbae478396759f0d5",
"name": "ISIC_0000003",
"updated": "2015-02-23T02:48:46.021000+00:00"
}]
You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:
input_file = open('input_file.txt')
data = json.load(input_file) # get the data list
for element in data: # iterate on each element of the list
# element is a dict
id = element['_id'] # get the id
print(id) # print it
If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:
ids = [ e['_id'] for e in data ] # get id from each element and create a list of them
As you can see the data is a list of dictionaries
for looping over data you need to use the following code
for each in data:
print each['_id']
print each['name']
print each['updated']
it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
Yes, but you can loop over all the dictionaries in your list and get the values for their '_id' keys. This can be done in a single line using list comprehension:
data = json.load(input_file)
ids = [value['_id'] for value in data]
print(ids)
['5436e3abbae478396759f0cf', '5436e3acbae478396759f0d1', '5436e3acbae478396759f0d3', '5436e3acbae478396759f0d5']
Another way to achieve this is using the map built-in function of python:
ids = map(lambda value: value['_id'], data)
This creates a function that returns the value of the key _id from a dictionary using a lambda expression and then returns a list with the return value from this function applied on every item in data

Categories

Resources