How to get a key from inside another key in python - python

Hey does anybody know how I would go about getting the value of a key which is already inside another key like this:
a = {"fruit":[{"oranges":['10']},{"apples":['11']}]}
print(a.get("fruit"))
I can get the value of "fruit" but how would I get the value of "oranges".
Thank you for any help in advance.

Let's format your dictionary and clearly see what you have:
a = {
"fruit": [
{
"oranges": ['10']
},
{
"apples": ['11']
}
]
}
So, a.get('fruit') gives you a list, which elements can be accessed with indexes.
So a['fruit'][0] gives you
{
"oranges": ['10']
}
and a['fruit'][1] gives you
{
"apples": ['11']
}
So in order to get the value of oranges you should go with:
a['fruit'][0]['oranges']
which will give you: ['10']. ['10'] is a list of its own. If you want to get only the value, you can do:
a['fruit'][0]['oranges'][0]

You just have to access the first element of the list inside fruits, and then access the key inside
print(a['fruit'][0]['oranges']

Related

Get an element of a list where something is static

I'm using an API where the request.json gives me back a list inside a list inside a list inside a list.
I recently got an answer how to access these lists and their elements.
However I don't know a way to get a specific list.
So it's like this:
{
"name1": {
},
"name2": {
"something1": 213,
"something2": [
{
"info1": 123,
"info2": 324
}
]
}
}
and i need to get info1 which is a variable from a list where info2 is which is static and does not change.
There's 10 "somethings" and info2 is an id.
How can I check for info2 while trying to get info1?
I used this to get info1:
r.json()['name2']['something2'][0]['info1']
but i need 'something2' to be match 'info2'
Basically I need info1 from somethingX where info2 = xyz(set known value)
r.json()['name2']['something2'][0]['info1']
always gives me the 1st item of the 'name2'
Loop through the dictionary elements.
data = r.json()['name2']
For val in data.values():
if val['info2'] == xyz:
print(val['info1'])
break

Iterate through a nested python dict

I have a JSON file that looks like this:
{
"returnCode": 200,
"message": "OK",
“people”: [
{
“details: {
"first": “joe”,
“last”: doe,
“id”: 1234567,
},
“otheDetails”: {
“employeeNum”: “0000111222”,
“res”: “USA”,
“address”: “123 main street”,
},
“moreDetails”: {
“family”: “yes”,
“siblings”: “no”,
“home”: “USA”,
},
},
{
“details: {
"first": “jane”,
“last”: doe,
“id”: 987654321,
},
“otheDetails”: {
“employeeNum”: “222333444”,
“res”: “UK”,
“address”: “321 nottingham dr”,
},
“moreDetails”: {
“family”: “yes”,
“siblings”: “yes”,
“home”: “UK,
},
}
This shows two entries, but really there are hundreds or more. I do not know the number of entries at the time the code is run.
My goal is to iterate through each entry and get the 'id' under "details". I load the JSON into a python dict named 'data' and am able to get the first 'id' by:
data['people'][0]['details']['id']
I can then get the second 'id' by incrementing the '0' to '1'. I know I can set i = 0 and then increment i, but since I do not know the number of entries, this does not work. Is there a better way?
Less pythonic then a list comprehension, but a simple for loop will work here.
You can first calculate the number of people in the people list and then loop over the list, pulling out each id at each iteration:
id_list = []
for i in range(len(data['people'])):
id_list.append(data['people'][i]['details']['id'])
You can use dict.get method in a list comprehension to avoid getting a KeyError on id. This way, you can fill dictionaries without ids with None:
ids = [dct['details'].get('id') for dct in data['people']]
If you still get KeyError, then that probably means some dcts in data['people'] don't have details key. In that case, it might be better to wrap this exercise in try/except. You may also want to identify which dcts don't have details key, which can be gathered using error_dct list (which you can uncomment out from below).
ids = []
#error_dct = []
for dct in data['people']:
try:
ids.append(dct['details']['id'])
except KeyError:
ids.append(None)
#error_dct.append(dct)
Output:
1234567
987654321

How to output a list of values to a json output with duplicate keys

I am brand new to python and have hit a roadblock I can't seem to figure out.
I have a list of values. This list could have 1 value or many.
['9589503164607', '9589503197375']
I need to output this in a json format. My current output looks like this:
"line_items": {"id": ["9589503164607", "9589503197375"]}
I need this:
{"line_items":[{"id":9589503164607},{"id":9589503197375}]}
Currently, I am using a dictionary for this value and the rest that go with this line. However, due to having duplicate keys ("id"), I feel this may be the wrong approach.
shop_data = {
"fulfillment": {
"location_id": cleanslid,
"tracking_number": trackingnumber,
"line_items": {
"id": iteminvids,
}
}
}
iteminvids is the list I referenced.
If anyone could point me in the right direction I would be so grateful!
Use a list comprehension to create a list of dictionaries.
"line_items": [{"id": item} for item in list_of_values]
If your original list is in lst, you can do
json.dumps({"line_items": [{"id": i} for i in lst}]})

Python: TypeError in referencing item in JSON feed

First, here is a sample JSON feed that I want to read in Python 2.7 with either simplejson or the built in JSON decoder. I am loading the .json file in Python and then searching for a key like "Apple" or "Orange" and when that key is found, I want to bring in the information for it like the types and quantities.
Right now there is only 3 items, but I want to be able to search one that may have up to 1000 items. Here is the code:
{
"fruits": [
{
"Apple": [
{
"type": "Gala",
"quant": 5
},
{
"type": "Honeycrisp",
"quant": 10
},
{
"type": "Red Delicious",
"quant": 4
}
]
},
{
"Banana": [
{
"type": "Plantain",
"quant": 5
}
]
},
{
"Orange": [
{
"type": "Blood",
"quant": 3
},
{
"type": "Navel",
"quant": 20
}
]
}
]
}
My sample Python code is as follows:
import simplejson as json
# Open file
fjson = open('/home/teg/projects/test/fruits.json', 'rb')
f = json.loads(fjson.read())
fjson.close()
# Search for fruit
if 'Orange' in json.dumps(f):
fruit = f['fruits']['Orange']
print(fruit)
else:
print('Orange does not exist')
But whenever I test it out, it gives me this error:
TypeError: list indices must be integers, not str
Was it wrong to have me do a json.dumps and instead should I have just checked the JSON feed as-is from the standard json.loads? I am getting this TypeError because I am not specifying the list index, but what if I don't know the index of that fruit?
Do I have to first search for a fruit and if it is there, get the index and then reference the index before the fruit like this?
fruit = f['fruits'][2]['Orange']
If so, how would I get the index of that fruit if it is found so I could then pull in the information? If you think the JSON is in the wrong format as well and is causing this issue, then I am up for that suggestion as well. I'm stuck on this and any help you guys have would be great. :-)
Your f type is list, it's a list of dictionary's with sub dictionary.
if 'Orange' in json.dumps(f): Will iterate the list and look at each item for Orange.
The problem is that f['fruits'] is a list so it expects an int number (place)
and not a dictionary key like ['Orange']
I think you should check your structure like #kindall said, if you still want to extract Orange this code will do the trick:
for value in f['fruits']:
if 'Orange' in value:
print value['Orange']
The problem is that the data structure has a list enclosing the dictionaries. If you have any control over the data source, that's the place to fix it. Otherwise, the best course is probably to post-process the data after parsing it to eliminate these extra list structures and merge the dictionaries in each list into a single dictionary. If you use an OrderedDict you can even retain the ordering of the items (which is probably why the list was used).
The square bracket in the line "fruits": [ should tell you that the item associated with fruits is (in Python parlance) a list rather than a dict and so cannot be indexed directly with a string like 'Oranges'. It sounds like you want to create a dict of fruits instead. You could do this by reformatting the input.
Or, if the input format is fixed: each item in your fruits list currently has a very specific format. Each item is a dict with exactly one key, and those keys are not duplicated between items. If those rules can be relied upon, it's pretty easy to write a small search routine—or the following code will convert a list-of-dicts into a dict:
fruits = dict(sum([x.items() for x in f['fruits']], []))
print fruits['Orange']

Python - dict full of identical values

Really can't get out of this...
Here's my python code:
for i in range(len(realjson)) :
store["Store"]={
"id" :realjson[i]['id'].strip(),
"retailer_id" :RETAILER_ID,
"name" :find(realjson[i]["title"],">","<").strip(),
"address" :realjson[i]["address"].strip(),
"city" :realjson[i]["address"].split(",")[-4].strip(),
"province" :realjson[i]["address"].split(",")[-3].strip(),
"group" :realjson[i]["address"].split(",")[-1].strip(),
"zip" :realjson[i]["address"].split(",")[-2].strip(),
"url" :"http://blabla.com?id="+realjson[i]["id"].strip(),
"lat" :realjson[i]["lat"].strip(),
"lng" :realjson[i]["lon"].strip(),
"phone" :realjson[i]["telephone_number"].replace("<br />Phone Number: ","").strip()
}
stores.append(store)
print stores[i]
When I print the list inside the for loop it works correctly.
Otherwise when I print the array outside the loop like this:
print storesit contains only the last element that I've appended repeated for the entire length of the list.
Do you have some advice to help me!
Thank you.
You reuse a mutable object in your loop:
store['Store']
Create a new copy in the loop instead:
newstore = store.copy()
newstore['Store'] = { ... }
store["Store"]={ ... }
if you expect this line to create new dictionary with just one key, then what you actually want is
store = {"Store": { ... }}

Categories

Resources