Json parse python error - python

I have the following dict. I would like to loop through this key and values
i.e for items in ice/cold, print "values"
[
{
"ice/cold": [
"vanilla",
"hotchoc",
"mango",
"banana"
]
},
{
"fire/hot": [
"barbecue",
"hotsalsa",
"sriracha",
"kirikiri"
]
},
{
"friendly/mild": [
"ketchup",
"mustard",
"ranch",
"dipster"
]
}
]
Tried this:
data='*above set*'
for key in data.items():
print value
but gives me error
AttributeError: 'list' object has no attribute 'items'

The data structure you have is a bit strange. You don't have a single dict, you have a list of dicts, each with a single key which itself contains a list. You could do this:
for item in data:
for key, value in item.items():
print value
but a better way would be to change the structure so you only have a single dict:
{
"ice/cold": [
"vanilla",
"hotchoc",
"mango",
"banana"
],
"fire/hot": [
"barbecue",
"hotsalsa",
"sriracha",
"kirikiri"
],
"friendly/mild": [
"ketchup",
"mustard",
"ranch",
"dipster"
]
}

here data is actually a list not a dictionary
and every index of list is a dictionary so just loop through all elements of list and see if it corresponds to desired dictionary
here is the code
data= [
{
"ice/cold": [
"vanilla",
"hotchoc",
"mango",
"banana"
]
},
{
"fire/hot": [
"barbecue",
"hotsalsa",
"sriracha",
"kirikiri"
]
},
{
"friendly/mild": [
"ketchup",
"mustard",
"ranch",
"dipster"
]
}
]
for items in data:
for key, value in items.iteritems():
if key == "ice/cold":
print value

Related

get data from a json

I want to get the data from a json. I have the idea of a loop to access all levels.
I have only been able to pull data from a single block.
print(output['body']['data'][0]['list'][0]['outUcastPkts'])
How do I get the other data?
import json,urllib.request
data = urllib.request.urlopen("http://172.0.0.0/statistic").read()
output = json.loads(data)
for elt in output['body']['data']:
print(output['body']['data'][0]['inUcastPktsAll'])
for elt in output['list']:
print(output['body']['data'][0]['list'][0]['outUcastPkts'])
{
"body": {
"data": [
{
"inUcastPktsAll": 3100617019,
"inMcastPktsAll": 7567,
"inBcastPktsAll": 8872,
"outPktsAll": 8585575441,
"outUcastPktsAll": 8220240108,
"outMcastPktsAll": 286184143,
"outBcastPktsAll": 79151190,
"list": [
{
"outUcastPkts": 117427359,
"outMcastPkts": 1990586,
"outBcastPkts": 246120
},
{
"outUcastPkts": 0,
"outMcastPkts": 0,
"outBcastPkts": 0
}
]
},
{
"inUcastPktsAll": 8269483865,
"inMcastPktsAll": 2405765,
"inBcastPktsAll": 124466,
"outPktsAll": 3101194852,
"outUcastPktsAll": 3101012296,
"outMcastPktsAll": 173409,
"outBcastPktsAll": 9147,
"list": [
{
"outUcastPkts": 3101012296,
"outMcastPkts": 90488,
"outBcastPkts": 9147
},
{
"outUcastPkts": 0,
"outMcastPkts": 0,
"outBcastPkts": 0
}
]
}
],
"msgs": [ "successful" ]
},
"header": {
"opCode": "1",
"token": "",
"state": "",
"version": 1
}
}
output = json.loads(data) #Type of output is a dictionary.
#Try to use ".get()" method.
print(output.get('body')) #Get values of key 'body'
print(output.get('body').get('data')) #Get a list of key 'data'
If a key doesn't exist, the '.get()' method will return None.
https://docs.python.org/3/library/stdtypes.html#dict.get
In python you can easily iterate over the objects of a list like so:
>>> l = [1, 2, 3, 7]
>>> for elem in l:
... print(elem)
...
1
2
3
7
This works regarding what can of object do you have in the list (integers, tuples, dictionaries). Having that in mind, your solution was not far off, you only to do the following changes:
for entry in output['body']['data']:
print(entry['inUcastPktsAll'])
for list_element in entry['list']:
print(list_element['outUcastPkts'])
This will give you the following for the json object you have provided:
3100617019
117427359
0
8269483865
3101012296
0

Elegant way of iterating list of dict python

I have a list of dictionary as below. I need to iterate the list of dictionary and remove the content of the parameters and set as an empty dictionary in sections dictionary.
input = [
{
"category":"Configuration",
"sections":[
{
"section_name":"Global",
"parameters":{
"name":"first",
"age":"second"
}
},
{
"section_name":"Operator",
"parameters":{
"adrress":"first",
"city":"first"
}
}
]
},
{
"category":"Module",
"sections":[
{
"section_name":"Global",
"parameters":{
"name":"first",
"age":"second"
}
}
]
}
]
Expected Output:
[
{
"category":"Configuration",
"sections":[
{
"section_name":"Global",
"parameters":{}
},
{
"section_name":"Operator",
"parameters":{}
}
]
},
{
"category":"Module",
"sections":[
{
"section_name":"Global",
"parameters":{}
}
]
}
]
My current code looks like below:
category_list = []
for categories in input:
sections_list = []
category_name_dict = {"category": categories["category"]}
for sections_dict in categories["sections"]:
section = {}
section["section_name"] = sections_dict['section_name']
section["parameters"] = {}
sections_list.append(section)
category_name_dict["sections"] = sections_list
category_list.append(category_name_dict)
Is there any elegant and more performant way to do compute this logic. Keys such as category, sections, section_name, and parameters are constants.
The easier way is not to rebuild the dictionary without the parameters, just clear it in every section:
for value in values:
for section in value['sections']:
section['parameters'] = {}
Code demo
Elegance is in the eye of the beholder, but rather than creating empty lists and dictionaries then filling them why not do it in one go with a list comprehension:
category_list = [
{
**category,
"sections": [
{
**section,
"parameters": {},
}
for section in category["sections"]
],
}
for category in input
]
This is more efficient and (in my opinion) makes it clearer that the intention is to change a single key.

Creating a new dict from a list of dicts

I have a list of dictionaries in the following format
data = [
{
"Members": [
"user11",
"user12",
"user13"
],
"Group": "Group1"
},
{
"Members": [
"user11",
"user21",
"user22",
"user23"
],
"Group": "Group2"
},
{
"Members": [
"user11",
"user22",
"user31",
"user32",
"user33",
],
"Group": "Group3"
}]
I'd like to return a dictionary where every user is a key and the value is a list of all the groups which they belong to. So for the above example, this dict would be:
newdict = {
"user11": ["Group1", "Group2", "Group3"]
"user12": ["Group1"],
"user13": ["Group1"],
"user21": ["Group2"],
"user22": ["Group2", "Group3"],
"user23": ["Group2"],
"user31": ["Group3"],
"user32": ["Group3"],
"user33": ["Group3"],
}
My initial attempt was using a defaultdict in a nested loop, but this is slow (and also isn't returning what I expected). Here was that attempt:
user_groups = defaultdict(list)
for user in users:
for item in data:
if user in item["Members"]:
user_groups[user].append(item["Group"])
Does anyone have any suggestions for improvement for speed, and also just a generally better way to do this?
Code
new_dict = {}
for d in data: # each item is dictionary
members = d["Members"]
for m in members:
# appending corresponding group for each member
new_dict.setdefault(m, []).append(d["Group"])
print(new_dict)
Out
{'user11': ['Group1', 'Group2', 'Group3'],
'user12': ['Group1'],
'user13': ['Group1'],
'user21': ['Group2'],
'user22': ['Group2', 'Group3'],
'user23': ['Group2'],
'user31': ['Group3'],
'user32': ['Group3'],
'user33': ['Group3']}

Check whether a given value is in a nested dictionary

I have this structure, converted using json.load(json)
jsonData = [ {
thing: [
name: 'a name',
keys: [
key1: 23123,
key2: 83422
]
thing: [
name: 'another name',
keys: [
key1: 67564,
key2: 93453
]
etc....
} ]
I have key1check = 67564,
I want to check if a thing's key1 matches this value
if key1check in val['thing']['keys']['key1'] for val in jsonData:
print ('key found, has name of: {}'.format(jsonData['thing']['name'])
Should this work? Is there a better was to do this?
Not quite:
in is for inclusion in a sequence, such as a string or a list. You're comparing integer values, so a simple == is what you need.
Your given structure isn't legal Python: you have brackets in several places where you're intending a dictionary; you need braces instead.
Otherwise, you're doing fine ... but you should not ask us if it will work: ask the Python interpreter by running the code.
Try this for your structure:
jsonData = [
{ "thing": {
"name": 'a name',
"keys": {
"key1": 23123,
"key2": 83422
} } },
{ "thing": {
"name": 'another name',
"keys": {
"key1": 67564,
"key2": 93453
} } }
]
You can loop through #Prune 's dictionary using something like this as long as the structure is consistent.
for item in jsonData:
if item['thing']['keys']['key1'] == key1check:
print("true")
else:
print("false")

How to update a dict value with Python

I have a dictionary like the following:
sample_dict = {
"matchings": [
{
"indices": [
0,
1,
2
],
"geometry": "hemo_Ab}gueC????",
"matched_points": [
[
-33.823845,
-70.619614
],
[
-33.823845,
-70.619614
],
[
-33.823845,
-70.619614
]
]
}
]
}
How can I update the geometry value?
You can loop through your matchings with this syntax:
for i, matching in enumerate(sample_json['matchings']):
# i is your matching's index
# matching is your current matching object
my_new_value = 'something'
sample_json["matchings"][i]["geometry"] = my_new_value

Categories