how to print json data - python

I have following json file and python code and i need output example...
json file
{"b": [{"1": "add"},{"2": "act"}],
"p": [{"add": "added"},{"act": "acted"}],
"pp": [{"add": "added"},{"act": "acted"}],
"s": [{"add": "adds"},{"act": "acts"}],
"ing": [{"add": "adding"},{"act": "acting"}]}
python
import json
data = json.load(open('jsonfile.json'))
#print data
out put example
>> b
>> p
>> pp
>> s
>> ing
any ideas how to do that?

This doesn't have anything to do with JSON. You have a dictionary, and you want to print the keys, which you can do with data.keys().

Here's a working example (it's emulating your file using io.StringIO):
import json
import io
jsonfile_json = io.StringIO("""
{
"b": [{"1": "add"}, {"2": "act"}],
"p": [{"add": "added"}, {"act": "acted"}],
"pp": [{"add": "added"}, {"act": "acted"}],
"s": [{"add": "adds"}, {"act": "acts"}],
"ing": [{"add": "adding"}, {"act": "acting"}]
}
""")
data = json.load(jsonfile_json)
for k in data.keys():
print(k)
As you can see, the answer to your question is using keys() method

For the sake of completeness:
d = {'p': 'pstuff', 'pp': 'ppstuff', 'b': 'bstuff', 's': 'sstuff'}
print('\n'.join(d))
Works in any version of Python. If you care about order:
print('\n'.join(sorted(d)))
Though in all honesty, I'd probably do Jim's approach:
print(*d, sep='\n'))

Simply unpack the keys with * in a print call, this provides the keys as positional arguments to print; use sep = '\n' if you want each key on a different line:
print(*data.keys(), sep= '\n')
This will print out:
b
pp
p
ing
s
As noted by #WayneWerner print(*data, sep='\n') is in effect like calling data.keys() and achieves the same result.

Related

Extract specific dictionaries from a list of nested dictionaries to a temp list

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)

Python Iterating New Data into nested dictionary

I have been working on a Python Role-Playing game and I have a function to import item data from a text file. The text file is structured as follows:
WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10
WEAPON 4 dagger_of_bluntness 2 5 3 1 0
WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0
The data importing goes like this:
def items_get():
import os
global items
items = {
"weapon":{},
"armour":{},
"potion":{},
"misc":{}
}
file_dir = ( os.getcwd() + '\Code\items.txt' )
file_in = open( file_dir, 'r')
for each_line in file_in:
line = file_in.readline()
line = line.split(' ')
if line[0] == "WEAPON":
weapon_id = line[1]
name = line[2]
attack_min = line[3]
attack_max = line[4]
range = line[5]
weight = line[6]
value = line[7]
weapon_data = {
"name": name.replace('_', ' '),
"atk_min": attack_min,
"atk_max": attack_max,
"rng": range,
"wt": weight,
"val": value,
}
items["weapon"][weapon_id] = {}
items["weapon"][weapon_id].update(weapon_data)
However, when I print items["weapon"], I get this:
{'4': {'wt': '1', 'atk_min': '2', 'atk_max': '5', 'val': '0', 'name': 'dagger of bluntness', 'rng': '3'}}
As you can see, there is only 1 item there. On other occasions I have had two even though I actually have 3 items listed. Why is this happening, and how do I get all 3 items in the dictionary?
Thanks!
:P
EDIT: Here is the data for the potions, in case you were wondering.
elif line.split()[0] == "POTION":
_, id, name, hp_bonus, atk_bonus, range_bonus, ac_bonus, str_bonus, con_bonus, dex_bonus, int_bonus, wis_bonus, cha_bonus, wt, val = line.split()
A healing potion looks like this in the file:
POTION 1 potion_of_healing 20 0 0 0 0 0 0 0 0 0 0.1 2
for each_line in file_in:
line = file_in.readline()
each_line already contains the next line, because iterating through a file-like object (say, with a for loop) causes it to go by lines.
On each iteration of the loop, the file pointer is advanced by one line (file-like objects, though rewindable, keep track of their last-accessed position), and then before anything is done it gets advanced once more by the readline(), so the only line that doesn't get skipped entirely is the middle one (4).
To fix this, use the loop variable (each_line) within the loop body directly and nix the file_in.readline().
#noname1014, I know you know this but I want to point out few of the problems with your code (that may occur in some special cases, e.g if you change your file name items.txt to new_items.txt, rare_fruits.txt etc.) and some suggestions.
Do not use \ as path separators in Windows. Use \\ otherwise you may get into problems. \Code\time_items.txt will be evaluated as \Code imeitems.txt because \t is TAB here.
Using \ only works in few cases if \ followed by any character A, p, n, t, ", ' etc. does not construct escape sequences like \n, \t, \f, \r, \b etc.
Have a look at the below example for clarification.
>>> import os
>>>
>>> print(os.getcwd() + '\Code\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code imeitems.txt
>>>
>>> print(os.getcwd() + '\Code\\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\timeitems.txt
>>>
>>> print(os.getcwd() + '\Code\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code
ewitems.txt
>>>
>>> print(os.getcwd() + '\\Code\\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\newitems.txt
>>>
>>> # Do not use it as it may work only in some cases if \ followed by any character does not construct escape sequences.
...
>>> os.getcwd() + '\Code\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> # Use \\ as path separators
...
>>> os.getcwd() + '\\Code\\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> print(os.getcwd() + '\Code\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
>>> print(os.getcwd() + '\\Code\\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
If your dictionay is huge and you are facing any issue while looking into its items, pretty it using json module, it has a function called dumps() which is used to pretty print list and dictionary objects.
It is ok to place import statements inside function but placing it on the top is a Pythonic way (https://www.python.org/dev/peps/pep-0008/#imports). It is good for large applications with multiple functions in the same module.
Use with statement for opening files, in this case you do not need to close files.
Your code is fine, I have just modified it as below.
import os
global items
import json
def items_get():
items = {
"weapon":{},
"armour":{},
"potion":{},
"misc":{}
}
# Do not use \ as path separators in Windows. Use \\ (\t, \n, \' have speacial meanings)
file_dir = ( os.getcwd() + '\\Code\\items.txt' )
with open( file_dir, 'r') as file_in:
lines = file_in.readlines();
# ['WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10\n', 'WEAPON 4 dagger_of_bluntness 2 5 3 1 0\n', 'WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0']
for each_line in lines:
# Use strip() to remove any leading/trailing whitespaces (\n, \t, spaces etc.)
line = each_line.strip().split(' ');
if line[0] == "WEAPON":
weapon_id = line[1]
name = line[2]
attack_min = line[3]
attack_max = line[4]
range = line[5]
weight = line[6]
value = line[7]
weapon_data = {
"name": name.replace('_', ' '),
"atk_min": attack_min,
"atk_max": attack_max,
"rng": range,
"wt": weight,
"val": value,
}
items["weapon"][weapon_id] = {}
items["weapon"][weapon_id].update(weapon_data)
return items
# Calling items_get() to get dictionary
items = items_get();
# Pretty printing dictionary using json.dumps()
print(json.dumps(items, indent=4))
ยป Output
{
"weapon": {
"3": {
"name": "sword of eventual obsolescence",
"atk_min": "6",
"atk_max": "10",
"rng": "2",
"wt": "0",
"val": "10"
},
"4": {
"name": "dagger of bluntness",
"atk_min": "2",
"atk_max": "5",
"rng": "3",
"wt": "1",
"val": "0"
},
"5": {
"name": "sword of extreme flimsiness",
"atk_min": "3",
"atk_max": "8",
"rng": "3",
"wt": "7",
"val": "0"
}
},
"armour": {},
"potion": {},
"misc": {}
}

How to select json data randomly

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'

matching dictionary values with the json data in Python

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"

Python CFFI convert structure to dictionary

There is a way to initialize structure with dictionary:
fooData= {'y': 1, 'x': 2}
fooStruct = ffi.new("foo_t*", fooData)
fooBuffer = ffi.buffer(fooStruct)
Is there some ready function to do the conversion?
fooStruct = ffi.new("foo_t*")
(ffi.buffer(fooStruct))[:] = fooBuffer
fooData= convert_to_python( fooStruct[0] )
Do I have to use ffi.typeof("foo_t").fields by myself?
I come up with this code so far:
def __convert_struct_field( s, fields ):
for field,fieldtype in fields:
if fieldtype.type.kind == 'primitive':
yield (field,getattr( s, field ))
else:
yield (field, convert_to_python( getattr( s, field ) ))
def convert_to_python(s):
type=ffi.typeof(s)
if type.kind == 'struct':
return dict(__convert_struct_field( s, type.fields ) )
elif type.kind == 'array':
if type.item.kind == 'primitive':
return [ s[i] for i in range(type.length) ]
else:
return [ convert_to_python(s[i]) for i in range(type.length) ]
elif type.kind == 'primitive':
return int(s)
Is there a faster way?
Arpegius' solution works fine for me, and is quite elegant. I implemented a solution based on Selso's suggestion to use inspect. dir() can substitute inspect.
from inspect import getmembers
from cffi import FFI
ffi = FFI()
from pprint import pprint
def cdata_dict(cd):
if isinstance(cd, ffi.CData):
try:
return ffi.string(cd)
except TypeError:
try:
return [cdata_dict(x) for x in cd]
except TypeError:
return {k: cdata_dict(v) for k, v in getmembers(cd)}
else:
return cd
foo = ffi.new("""
struct Foo {
char name[6];
struct {
int a, b[3];
} item;
} *""",{
'name': b"Foo",
'item': {'a': 3, 'b': [1, 2, 3]}
})
pprint(cdata_dict(foo))
Output:
{'item': {'a': 3, 'b': [1, 2, 3]}, 'name': b'Foo'}
This code infortunately does not work for me, as some struct members are "pointer" types, it leads to storing "none" in the dict.
I am a Python noob, but maybe the inspect module would be another starting point, and a shorter way to print "simple" data. Then we would iterate over the result in order to unroll data structure.
For example with the following example :
struct foo {
int a;
char b[10];
};
Using inspect.getmembers( obj ) I have the following result :
[('a', 10), ('b', <cdata 'char[10]' 0x7f0be10e2824>)]
Your code is fine.
Even if there was a built-in way in CFFI, it would not be what you need here. Indeed, you can say ffi.new("foo_t*", {'p': p1}) where p1 is another cdata, but you cannot recursively pass a dictionary containing more dictionaries. The same would be true in the opposite direction: you would get a dictionary that maps field names to "values", but the values themselves would be more cdata objects anyway, and not recursively more dictionaries.

Categories

Resources