This question already has answers here:
Accessing value inside nested dictionaries [duplicate]
(5 answers)
Closed 2 years ago.
How to access an element inside a nested dictionary in python?
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Indexing myfamily yields another dict, which you index like any other.
>>> myfamily["child1"]["name"]
'Emil'
You can easily access a child by using myfamily["child1"]
You can also access all keys by calling the keys() method on the myfamily variable
You can treat sub dictionaries just like a new dictionary
myfamily['child1']['year']
If you'd like to access the elements of myfamily, you can refer to those as myfamily['child1'], and that will return:
{
"name" : "Emil",
"year" : 2004
}
If child1 was its own directory, you were refer to elements in that as child1['name'] or child1['year']. Extending that to myfamily['child1'], you can access elements in child1 by identifying the element you want, like myfamily['child1']['name'] or myfamily['child1']['year'].
Why doesn't myfamily[child1['name']] work? If we separate our pieces, child1['name'] contains Emil. Substitute that for child1['name'] in myfamily[child1['name']], and we have myfamily['Emil']. That element doesn't exist in the myfamily dictionary, and will fail.
Related
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']
This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 1 year ago.
Given my sample array:
json_data = data: [
{
'item_name' : "bag",
'item_price' : 12.99,
'item_stock' : 55
},
{
'item_name' : "jacket",
'item_price' : 8.99,
'item_stock' : 42
},
{
'security_check' : "maximum",
'item_name' : "jewelry",
'item_stock' : 10
},
{
'security_check' : "minimum",
'item_name' : "leather",
'item_stock' : 5
}
]
i want to find elements with the "security_check" element. some elements do not have that and im trying to get the item_name of elements with security_check
This is the function im currently calling:
def array_parse_for_item_name(json_data, name):
for entry in json_object:
if entry["security_check"] in json_object:
print(str(entry["item_name"]))
print(str(entry["item_stock"]))
but right now all im getting is: KeyError: 'security_check' and i assume it's because some elements do not have that key
Any help would be much appreciated. Thanks in advance.
Check if it is one of keys rather than try retrieve its' value, i.e. replace
if entry["security_check"] in json_object
using
if "security_check" in entry.keys()
This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 4 years ago.
I'm trying to add a third value to existing dictionary keys in Python. I'm sure this is probably easy, but I'm fairly new to coding so each way I've tried has thrown an error. Below is an example of what I tried which resulted in a syntax error. I also tried making the colon an equal sign but I got the message can't assign to a literal which I figure is due to the presence of two different = in the same line of code.
student = [
{ "name": "Kellie", "student_id": 12345},
{ "name": "James", "student_id": 39875},
{ "name": "Katie", "student_id": 24680},
]
student[0] = "lastName" : "Vee"
student[1] = "lastName" : "Tee"
student[2] = "lastName" : "Zee"
Try to add element like this:
student[0]["grade"] = "1"
It will add here: { "name": "Kellie", "student_id": 12345} new key "grade" and asign the value of 1.
This question already has answers here:
How can I remove a key from a Python dictionary?
(11 answers)
Closed 7 years ago.
My Webservice call to Mongo returns following JSON. I need to iterate this JSON value and remove the Item - product_language as it contain NULL/Empty string.
ANy thoughts on how to do this?
Python 3.4 version.
{
"prod_doc_key" : "613509",
"metadata" : {
"channel_availability_for" : {
"description" : "Kiosk and Web",
"id" : 0
},
"dd_sold_out_flag" : 0,
"dd_units_sold_flag" : 0,
"display_type_id" : {
"id" : 0
},
"preorder_flag" : 0,
"price_in_cart_flag" : 0,
"product_language" : "",
"product_type" : {
"id" : 0,
"name" : "Product"
},
"promotion_flag" : 0,
"published" : 1,
"rebate_flag" : 0
}
}
Load it with json, then remove the key if it's empty:
import json
item =json.loads(src)
if 'product_language' in item and not item['product_language']:
item.pop('product_language')
in Python, empty strings are equal to False.
use json module to load the json.
import json
with open('demo.txt','r+') as f:
dic=json.load(f)
try:
if dic['metadata']["product_language"]:
del dic['metadata']["product_language"]
except KeyError:
print "Key doesn't exist"
print dic
Note that, here dic is a dictionary, you can be sure about it by printing type(dic). So, you can can perform any dictionary operation on it, for example, I deleted a key of dic. To iterate through the dic, do:
for key,value in dic.iteritems():
#do_something
You can remove a key k from a dictionary d with the syntax:
del d[k]
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": { ... }}