How to append list of dictionary in python? - python

I have to update the JSON by appending another list named "Stage3" under "Stage2" in python.
Initially, the JSON format is:
"Stage1":{
"Stage2":[
{
...
}
]
}
After adding "Stage3".How I want is:
Expected JSON Format:
"Stage1":{
"Stage2":[
{
...
"Stage3":[
{
...
},
{
...
}
]
}
]
}
Python
Stage1 = {}
Stage1['Stage2'] = []
Stage3 = [#<Where i'm having some dicitionary value>#]
How to append "Stage3" data inside this JSON?
Thanks in advance

You can do this:
mydict['Stage1']['Stage2'].append({"Stage3":"valueof3"})
where mydict have assigned dictionary value.
Check this:
https://repl.it/repls/CourteousGreenDownloads

Try this
import json
Stage1 = {}
Stage1['Stage2'] = [{}]
Stage3 = [{'a': 1}, {'b': 2}]
Stage1['Stage2'][0]['Stage3'] = Stage3
res = {'Stage1': Stage1}
print(json.dumps(res))
Output:
{
"Stage1": {
"Stage2": [
{
"Stage3": [
{
"a": 1
},
{
"b": 2
}
]
}
]
}
}

Related

Iterating JSON key value pairs over another JSON file and create a new json as per the output

I am trying to create a JSON file from two JSON files. Here I am reading the key value pairs from input.json and searching the matches in the secondary.json file and finally dumping the output to a new json file.
In the output of test.py I am expecting
{'tire1': {'source': ['test1', 'test2', 'test3']},
'tire6': {'source': ['test10', 'test21', 'test33']}}
instead of
{'tire1': {'source': ['test10', 'test21', 'test33']},
'tire6': {'source': ['test10', 'test21', 'test33']}}
But do not know what's wrong.
test.py
import json
import re
def findkeysvalues(inputDict, key):
if isinstance(inputDict, list):
for i in inputDict:
for x in findkeysvalues(i, key):
yield x
if isinstance(inputDict, dict):
if key in inputDict:
yield inputDict[key]
for j in inputDict.values():
for x in findkeysvalues(j, key):
yield x
def process_JSON_value(jsonFileInput, parentInputKey, key):
with open(jsonFileInput) as jsonFile:
data = json.load(jsonFile)
Dict = { }
for i in data:
if i == parentInputKey:
Dict[i] = data[i]
return list(findkeysvalues(Dict, key))
def createRulesJSON():
with open("input.json") as jsonFile:
data = json.load(jsonFile)
Dict = { }
rules_items_source = list(findkeysvalues(data, "source"))
for p in data:
Dict[p] = { }
for i in rules_items_source:
x = re.findall("\w+", i[0])
sourceItems = process_JSON_value("secondary.json", x[0], "compname")
Dict[p]['source'] = sourceItems
print(Dict)
createRulesJSON()
input.json
{
"tire1": {
"source": [ "{{ 'TEX' | YYYYYYY | join }}" ],
"dest": [ "{{ Microservice.host }}" ],
"port": "555"
},
"tire6": {
"source": [ "{{ 'REP' | LLLLLL | join }}" ],
"dest": [ "{{ Microservice.host2 }}" ],
"port": "555"
}
}
secondary.json
{
"client": {
"name": "anyname"
},
"PEP": {
"tire2": {
"tire3": {
"compname": "test1"
},
"tire4": {
"compname": "test2"
},
"tire5": {
"compname": "test3"
}
}
},
"REP": {
"tire2": {
"cmpname": "vendor1",
"tire3": {
"compname": "test10"
},
"tire4": {
"compname": "test21"
},
"tire5": {
"compname": "test33"
}
}
},
"Microservice": {
"host": "ttttttttttttttttttttt",
"host2": "GGGGGGGGGGGGGGGGGGGGGGGG"
}
}
Two issues:
Your nested loops in createRulesJSON create a Cartesian product on data. The first loop gets all keys from the data, and the nested loop extracts the three-letter code from all data. So you will combine one key with a code that was extracted from the other key's data. There is no attempt to keep these two informations associated, yet that is what you need.
To fix that, change this:
rules_items_source = list(findkeysvalues(data, "source"))
for p in data:
To:
for p in data:
rules_items_source = list(findkeysvalues(data[p], "source"))
From the expected output it seems that you want to map the code "TEX" (in the first file) with the code "PEP" (in the second file). There is nothing that maps these two codes to eachother.
To fix that, I will just assume that you'll correct in one of your files the code to match the other code.

How to access the following list and dictionary values in Python3?

{
"list":[
{
"a":1,
"b":2,
"c":3,
"d":{
"d1":10,
"d2":20,
"d3":30
},
"e":4,
"f":5,
"g":[
{
"g1":100,
"g2":200,
"g3":300
}
],
"h":6
}
]
}
I want to access d1, e, g1, h. How can I do it?
I have corrected your JSON string to this equivalent valid JSON string:
{
"list":[
{
"a":1,
"b":2,
"c":3,
"d":{
"d1":10,
"d2":20,
"d3":30
},
"e":4,
"f":5,
"g":[
{
"g1":100,
"g2":200,
"g3":300
}
],
"h":6
}
]
}
import json
# some JSON:
x = '{"list":[{"a":1,"b":2,"c":3,"d":{"d1":10,"d2":20,"d3":30},"e":4,"f":5,"g":[{"g1":100,"g2":200,"g3":300}],"h":6}]}'
# parse x:
d = json.loads(x)
print(d["list"][0]["d"]["d1"])
print(d["list"][0]["e"])
print(d["list"][0]["g"][0]["g1"])
print(d["list"][0]["h"])
Your question is lacking a lot of informations.
Let's suppose your overall dict is called dictionnary. To access :
d1 : dictionnary['list'][0]['d']['d1']
e : dictionnary['list'][0]['e']
g1 : dictionnary['list'][0]['g'][0]['g1']
h : dictionnary['list'][0]['h']

How to add key to existing dictionary?

I am using python3 and trying to figure out the easiest way to add another layer to my dictionary. I have a dictionary that looks like this.
{ "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
How can I add name into the existing dictionary?
{ "name": { "block1": [ "brian" ], "block2": [ "angel" ], "block3": [ "sally" ] } }
d1 = { "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
d1 = {"name":d1}
print (d1)

Pull key from json file when values is known (groovy or python)

Is there any way to pull the key from JSON if the only thing I know is the value? (In groovy or python)
An example:
I know the "_number" value and I need a key.
So let's say, known _number is 2 and as an output, I should get dsf34f43f34f34f
{
"id": "8e37ecadf4908f79d58080e6ddbc",
"project": "some_project",
"branch": "master",
"current_revision": "3rtgfgdfg2fdsf",
"revisions": {
"43g5g534534rf34f43f": {
"_number": 3,
"created": "2019-04-16 09:03:07.459000000",
"uploader": {
"_account_id": 4
},
"description": "Rebase"
},
"dsf34f43f34f34f": {
"_number": 2,
"created": "2019-04-02 10:54:14.682000000",
"uploader": {
"_account_id": 2
},
"description": "Rebase"
}
}
}
With Groovy:
def json = new groovy.json.JsonSlurper().parse("x.json" as File)
println(json.revisions.findResult{ it.value._number==2 ? it.key : null })
// => dsf34f43f34f34f
Python 3: (assuming that data is saved in data.json):
import json
with open('data.json') as f:
json_data = json.load(f)
for rev, revdata in json_data['revisions'].items():
if revdata['_number'] == 2:
print(rev)
Prints all revs where _number equals 2.
using dict-comprehension:
print({k for k,v in d['revisions'].items() if v.get('_number') == 2})
OUTPUT:
{'dsf34f43f34f34f'}

Merge list of dict into one dict in python

I have the following list of dicts in python.
[
{
"US": {
"Intial0": 12.515
},
{
"GE": {
"Intial0": 11.861
}
},
{
"US": {
"Final0": 81.159
}
},
{
"GE": {
"Final0": 12.9835
}
}
]
I want the final list of dicts as
[{"US": {"Initial0":12.515, "Final0": 81.159}}, {"GE": {"Initial0": 11.861, "Final0": 12.9835}}]
I am struggling with this from quite some time . Any help?
You could use Python's defaultdict as follows:
from collections import defaultdict
lod = [
{"US": {"Intial0": 12.515}},
{"GE": {"Intial0": 11.861}},
{"US": {"Final0": 81.159}},
{"GE": {"Final0": 12.9835}}]
output = defaultdict(dict)
for d in lod:
output[d.keys()[0]].update(d.values()[0])
print output
For the data given, this would display the following:
defaultdict(<type 'dict'>, {'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}})
Or you could convert it back to a standard Python dictionary with print dict(output) giving:
{'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}}
list1=[{"US": {"Intial0": 12.515}},{"GE": {"Intial0": 11.861}},{"US": {"Final0": 81.159}},{"GE": {"Final0": 12.9835}}]
dict_US={}
dict_GE={}
for dict_x in list1:
if dict_x.keys()==['US']:
dict_US.update(dict_x["US"])
if dict_x.keys()==['GE']:
dict_GE.update(dict_x["GE"])
list2=[{"US":dict_US},{"GE":dict_GE}]
print list2

Categories

Resources