I have a json file something of this sort
{"label" :
[
{"confidence": 1.0, "Arm_upVector": "(0.108535, 0.987291, 0.116085)", "bone_direction": ["(0, 0, 0)", "(0.354117, -0.111147, 0.928573)", "(0.144538, -0.00496286, 0.989487)", "(0.446597, -0.15941, 0.88042)", "(-0.145324, -0.134126, 0.980251)", "(0.0181324, 0.250534, 0.967938)", "(0.0234257, 0.321893, 0.946486)", "(0.0270345, 0.370523, 0.92843)", "(-0.278899, -0.118777, 0.952947)", "(-0.233781, 0.223357, 0.946287)", "(-0.202379, 0.307555, 0.92976)", "(-0.179014, 0.365886, 0.913281)", "(-0.419468, -0.0960966, 0.902669)", "(-0.311356, 0.246008, 0.917898)", "(-0.270254, 0.328053, 0.905176)", "(-0.239766, 0.384412, 0.891482)", "(-0.545443, -0.112047, 0.830625)", "(-0.571996, 0.254741, 0.779697)", "(-0.541193, 0.297035, 0.78669)", "(-0.517904, 0.327198, 0.79039)"], "handtype": "Right hand", "hand": 1, "finger": 5, "FrameId": 132251}
]
}
I am trying to match the handtype present in the json file with the handtype in my dictionary.
my dictionary is as follows:
data1={
'FrameId':frame.id,
'hand' : len(frame.hands),
'handtype': handType,
'Arm_upVector': str(basis.y_basis),
'confidence': confidence,
'finger': len(frame.fingers),
'bone_direction' : list1
# 'pinch_strength': pinch,
# 'grab_strength' : strength,
# 'vector_direction' : str(fingerDirection)
}
if confidence==1:
with open('data.json') as f:
s=json.load(f)
for row in s['label']:
if data1['handtype'] == s['handtype']:
print "match found"
I am trying to do something of this sort. Please help
You need to compare row['handtype'] with data1['handtype'] like following:
if confidence==1:
with open('data.json') as f:
s=json.load(f)
for row in s['label']:
if data1['handtype'] == row['handtype']:
print "match found"
Related
Here I have this code:
import emoji
txt = str(input('String: '))
for emoji in emoji.EMOJI_DATA:
if emoji.EMOJI_DATA['en'] == txt:
print('The emoji would be here')
With that code, I get this error: Keyerror['en'], because of course, there is no 'en' within EMOJI_DATA, so, how could I access what would be the emoji key here?
EMOJI_DATA = {
'🥇': {
'en' : ':1st_place_medal:',
'status' : emoji.STATUS["fully_qualified"],
'E' : 3,
'de': ':goldmedaille:',
'es': ':medalla_de_oro:',
'fr': ':médaille_d’or:',
'pt': ':medalha_de_ouro:',
'it': ':medaglia_d’oro:'
},
...
}
Your code should be like this as you can't access inner key directly.
import emoji
txt = str(input('String: '))
for emoji in emoji.EMOJI_DATA:
if emoji.EMOJI_DATA['🥇']['en'] == txt:
print('The emoji would be here')
First of all , you don't need to loop through all items in emoji.EMOJI_DATA . You may make use of lambda which is more efficient.
import emoji
txt = ":1st_place_medal:"
emojiList = emoji.EMOJI_DATA
filteredList = list(filter(lambda x: x[1]["en"] == txt, emojiList.items()))
if(len(filteredList) > 0):
print("Emoji is ",filteredList[0][0])
print("Details are ",filteredList[0][1])
else:
print("Not Found")
On the multidimensional JSON below i had extracted the "width" and "height" values as i want to append on an empty table/array and use them later for calculations. On the following JSON.
[
{
"frame_id":1,
"filename":"bake/IMG_20210930_090024.jpg",
"objects": [
{"class_id":0, "name":"brick", "relative_coordinates":{"left_x":1279, "top_y": 991, "width": 922, "height":1164},"relevant":true}
]
},
{
"frame_id":2,
"filename":"bake/IMG_20210930_090017.jpg",
"objects": [
{"class_id":1, "name":"limestone", "relative_coordinates":{"left_x":1672, "top_y":1536, "width": 651, "height": 623},"relevant":true}
]
}
]
My code and result:
with open('/home/pan/output/result.json') as json_data:
data = json.load(json_data)
for item in data:
for row in item.get('objects', []):
print(row['class_id'], row['relative_coordinates']['width'],row['relative_coordinates']['height'])
0 922 1164
1 651 623
My main question would be that i would like to show the results only for "class_id":0 for width and height.
Also whats the best way to append those values through the console or an empty array[] and make calculations later?
You can try this:
value_list = []
with open('result.json') as json_data:
data = json.load(json_data)
for item in data:
for row in item.get('objects', []):
if row['class_id'] == 0:
print(row['class_id'], row['relative_coordinates']['width'], row['relative_coordinates']['height'])
value_list.append(row['relative_coordinates']['width'])
value_list.append(row['relative_coordinates']['height'])
print(value_list)
Output:
0 922 1164
[922, 1164]
You get to your data by slogging through the dicts and lists one by one.
width = -1
height = -1
for item in data:
if item['objects'][0]['class_id'] == 0:
width = item['objects'][0]['relative_coordinates']['width']
height ​= item['objects'][0]['relative_coordinates']['height']
break
Just adding a if condition in your code will give the expected results as below:
data = None
with open('/home/pan/output/result.json') as json_data:
data = json.load(json_data)
co_ordinates = []
for item in data:
for row in item.get('objects', []):
if row['class_id'] == 0:
co_ordinates.append(row['relative_coordinates']['width'])
co_ordinates.append(row['relative_coordinates']['height'])
break
print (co_ordinates)
Output:
[922, 1164]
I'm looking for any suggestions to resolve an issue I'm facing. It might seem as a simple problem, but after a few days trying to find an answer - I think it is not anymore.
I'm receiving data (StringType) in a following JSON-like format, and there is a requirement to turn it into flat key-value pair dictionary. Here is a payload sample:
s = """{"status": "active", "name": "{\"first\": \"John\", \"last\": \"Smith\"}", "street_address": "100 \"Y\" Street"}"""
and the desired output should look like this:
{'status': 'active', 'name_first': 'John', 'name_last': 'Smith', 'street_address': '100 "Y" Street'}
The issue is I can't find a way to turn original string (s) into a dictionary. If I can achieve that the flattening part is working perfectly fine.
import json
import collections
import ast
#############################################################
# Flatten complex structure into a flat dictionary
#############################################################
def flatten_dictionary(dictionary, parent_key=False, separator='_', value_to_str=True):
"""
Turn a nested complex json into a flattened dictionary
:param dictionary: The dictionary to flatten
:param parent_key: The string to prepend to dictionary's keys
:param separator: The string used to separate flattened keys
:param value_to_str: Force all returned values to string type
:return: A flattened dictionary
"""
items = []
for key, value in dictionary.items():
new_key = str(parent_key) + separator + key if parent_key else key
try:
value = json.loads(value)
except BaseException:
value = value
if isinstance(value, collections.MutableMapping):
if not value.items():
items.append((new_key,None))
else:
items.extend(flatten_dictionary(value, new_key, separator).items())
elif isinstance(value, list):
if len(value):
for k, v in enumerate(value):
items.extend(flatten_dictionary({str(k): (str(v) if value_to_str else v)}, new_key).items())
else:
items.append((new_key,None))
else:
items.append((new_key, (str(value) if value_to_str else value)))
return dict(items)
# Data sample; sting and dictionary
s = """{"status": "active", "name": "{\"first\": \"John\", \"last\": \"Smith\"}", "street_address": "100 \"Y\" Street"}"""
d = {"status": "active", "name": "{\"first\": \"John\", \"last\": \"Smith\"}", "street_address": "100 \"Y\" Street"}
# Works for dictionary type
print(flatten_dictionary(d))
# Doesn't work for string type, for any of the below methods
e = eval(s)
# a = ast.literal_eval(s)
# j = json.loads(s)
Try:
import json
import re
def jsonify(s):
s = s.replace('"{','{').replace('}"','}')
s = re.sub(r'street_address":\s+"(.+)"(.+)"(.+)"', r'street_address": "\1\2\3"',s)
return json.loads(s)
If you must keep the quotes around Y, try:
def jsonify(s):
s = s.replace('"{','{').replace('}"','}')
search = re.search(r'street_address":\s+"(.+)"(.+)"(.+)"',s)
if search:
s = re.sub(r'street_address":\s+"(.+)"(.+)"(.+)"', r'street_address": "\1\2\3"',s)
dict_version = json.loads(s)
dict_version['street_address'] = dict_version['street_address'].replace(search.group(2),'"'+search.group(2)+'"')
return dict_version
A more generalized attempt:
def jsonify(s):
pattern = r'(?<=[,}])\s*"(.[^\{\}:,]+?)":\s+"([^\{\}:,]+?)"([^\{\}:,]+?)"([^\{\}:,]+?)"([,\}])'
s = s.replace('"{','{').replace('}"','}')
search = re.search(pattern,s)
matches = []
if search:
matches = re.findall(pattern,s)
s = re.sub(pattern, r'"\1": "\2\3\4"\5',s)
dict_version = json.loads(s)
for match in matches:
dict_version[match[0]] = dict_version[match[0]].replace(match[2],'"'+match[2]+'"')
return dict_version
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.
I tried this:
new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
def approachA():
for data in new_users: # new_users is a list of nested dictionaries
if data == '0':
print("found 0")
keys = data.keys()
for key in keys:
if key == '0':
key.pop() # tried to deleted delete the elements at first
It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.
This is a simple version of what I am trying to do:
[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]
So basically the keys with value "0" get copied to a temp list of dictionaries.
As I mentioned in a comment I'm not sure this will solve your problem, but based on the sample transformation you gave, here's one way to achieve it:
LIST_IN = [{"name": {"book1": "0", "book2": "1", "book3": "0"}}]
def proccess(list_in):
result = []
for this_dict in list_in:
for key in this_dict["name"]:
if this_dict["name"][key] == "0":
result.append({key: this_dict["name"][key]})
return result
print(proccess(LIST_IN))
This should accomplish the "sample" snippet. Please give some additional details if this is not what you were trying.
def solve_nested(nested_dict: list) -> list:
result = list()
for dictionary in nested_dict:
for k, v in dictionary.items():
for _k, _v in v.items():
if _v == '0':
result.append({_k: _v})
return result
if __name__ == '__main__':
print(solve_nested([{"name": {"book1": "0", "book2": "1", "book3": "0"}}]))
If you're interested in recursion, the below example ought to get you going:
# d_xy => x = nest level
# y = dictionary item in nest level x
d = {'d_00' : {'d_10' : {'d_20' : 0,
'd_21' : 43,
'd_22' : 12},
'd_11' : 4,
'd_12' : 0,
'd_13' : 1},
'd_01' : 0,
'd_02' : {'d_14' : {'d_23' : 0,
'd_24' : 1,
'd_25' : 0},
'd_15' : 4,
'd_16' : {'d_26' : 0,
'd_27' : {'d_30' : 3,
'd_31' : 0,
'd_32' : {'d_40' : 0},
'd_33' : 0},
'd_28' : 1},
'd_17' : 0}}
important_items = []
def get_0_key_values(dic):
for key in dic:
if type(dic[key]) == dict:
get_0_key_values(dic[key])
else:
if dic[key] == 0:
important_items.append({key : dic[key]})
get_0_key_values(d)
print(important_items)
I have following json file and I need a way to randomly select json data and prints its value.
json file :
{
"base": [{"1": "add"},{"2": "act"}],
"past": [{"add": "added"},{"act": "acted"}],
"past-participle": [{"add": "added"},{"act": "acted"}],
"s-es-ies": [{"add": "adds"},{"act": "acts"}],
"ing": [{"add": "adding"},{"act": "acting"}]
}
example
user_input = 'past' >> past
code randomly selects 'add' or 'act' from past >> add
prints out its value >> added
Use random.choice supplying as choices the sequence contained for the selected key:
user_input = input('> ')
> past
list(choice(j[user_input]).values())[0]
Out[177]: 'added'
Factor it in a function to make it more compact:
def random_json_val(json_obj, k):
return list(choice(json_obj[k]).values())[0]
Calling it gets you a random value for a given k:
>>> random_json_val(j, 'past')
'added'
>>> random_json_val(j, 'past')
'acted'
>>> random_json_val(j, 's-es-ies')
'acts'