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]
Related
This question already has answers here:
Use Variable As Dictionary Key Set
(2 answers)
How to use a dot "." to access members of dictionary?
(36 answers)
Closed last month.
Lets say I have some json like so store in a variable called data
{
"print": {
"ams": { "exists": 1},
"fan_speed": 29,
"reports": [
{"name": "foo"},
{"name": "bar"}
]
}
}
Now I've got a variable which is the key i want to return stored in a variable called key for example print.fan_speed, print.ams.exists, print.reports[0].name
What I want to is something like data.get(key). What is the best way to approach this?
The following should work its way into your data, including indexing into lists:
import re
data = {
"print": {
"ams": { "exists": 1},
"fan_speed": 29,
"reports": [
{"name": "foo"},
{"name": "bar"}
]
}
}
def value_of(data, location):
for part in location.split("."):
match = re.match(r"(.*)\[(\d+)\]$", part)
if match:
name, index = match.groups()
data = data.get(name)[int(index)]
else:
data = data.get(part)
if not data:
return None
return data
print(value_of(data, "print.ams.exists"))
print(value_of(data, "print.reports[1].name"))
Result:
1
bar
It could do with a little rationalisation as it will return None for a non-existent key, but will error on a bad index - it should do one or the other depending on your requirements but the concept is there.
The concept is to take each '.' separated element of the string in turn, using it to dig further into the data structure. If the element matches the syntax of 'name[index]' using the regex, the component is treated as a list and the indexth element is extracted.
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:
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.
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.
The collection structure that I have is as follows:
defaultdict(
lambda: {
'_id' : None,
'stuff' : [defaultdict(lambda : 0)]
})
I am trying to initialise a list of dictionaries that I'll keep on updating in a way that if a dictionary's key already exists then I'll increase its value by 1 otherwise I'll update the list of dictionary with the new key, value pair. e.g. is the value of stuff is [] and I have come across a value val then the value of stuff will be [{'val' : 1}] and further if I get a value val2 then stuff = [{'val' : 1}, {'val2' : 1}] and again if I get val, stuff should be [{'val' : 2}, {'val2' : 1}].
I tried this:
table.update({'_id' : data['_id']}, \
{'$inc' : {"stuff.$."+keyvalue : 1}})
where, data is a JSON object having an _id and a list of dictionaries stuff. Running this I received an OperationFailure: The positional operator did not find the match needed from the query.
I cannot figure out what to do? I am a Mongo newbie.
Quoting the documentation
When used with update operations, e.g. db.collection.update() and db.collection.findAndModify(),
the positional $ operator acts as a placeholder for the first element that matches the query document, and
the array field must appear as part of the query document.
So the stuff array should appear in your query. Now since you are doing conditional update you need to check if your array already has any subdocument with your keyvalue using $exists.
if not table.find_one({ "_id": data['_id'], "stuff": {"$elemMatch": {keyvalue: { "$exists" : True }}}}):
table.update({ "_id": data['_id'] }, { "$push": { "stuff": { keyvalue: 1 }}})
else:
table.update({ "_id": data['_id'], "stuff": { "$elemMatch": { keyvalue: { "$exists" : True}}}}, { "$inc": { "stuff.$." + keyvalue: 1}})