This question already has answers here:
Filter dict to contain only certain keys?
(22 answers)
Closed 2 years ago.
I have my dict as follows
user_model = {
"users": [{
"userid": 100,
"level": 1,
"score": 5,
},
{
"userid": 101,
"level": 2,
"score": 5,
},
{
"userid": 100,
"level": 2,
"score": 5,
},
{
"userid": 103,
"level": 1,
"score": 2,
}
]
}
Can someone please point me in right direction to update only "score" if my "userid" is 103 and "level" is 2.
Thanks
This way you can list all the data in your json:
for item in user_model['users']:
print(item) #check items
if item['userid'] == 103:
item['score'] = 25
print(item)
Related
{
"id": 1,
"resourceAttributes": {
"siteId": "100"
},
},
{
"id": 2,
"resourceAttributes": {
"siteId": "200"
},
},
{
"id": 3,
"resourceAttributes": {
"siteId": "100"
},
},
I have this kind of json and as a result I want to show output like this
SiteId100 occurance 2
SiteId200 occurance 1
this out put is on basis of occurrences of site id value like if siteId 100 values occurred in 2 objects I need to show number of occurrences with count. I am trying something like getting all possible site ids and then removing duplicates and then finding one by one but seems that is not a neat solution.
you need to use colections.Counter. here's the full code:
from collections import Counter
data = [
{
"id": 1,
"resourceAttributes": {
"siteId": "100"
},
},
{
"id": 2,
"resourceAttributes": {
"siteId": "200"
},
},
{
"id": 3,
"resourceAttributes": {
"siteId": "100"
},
}
]
c = Counter(s.get("resourceAttributes").get("siteId") for s in data)
for k, v in c.items():
print("siteId{} occurance: {}".format(k, v))
output:
siteId100 occurance: 2
siteId200 occurance: 1
I have dictionary formate which contain 4 lists and in the end, I want to convert it into JSON.
modelOutput = {
"projectYears": 1,
"RevSev": [
{
"name": "FixedSavings",
"fixedSavingsCost": []
}, {
"name": "variableSavings",
"variableSavingsCost": []
}, {
"name": "startUpSavings",
"startUpSavingsCost": []
}, {
"name": "shutDownSavings",
"shutDownSavingsCost": []
},
],
}
SO if the projectYear value is 2 then there will be 2 dictionaries with 4 lists(Cost) with 2 random values in it in each dictionary.
expected output:
#if projectYear = 2
modelOutput = {
"projectYears": 1,
"RevSev": [
{
"name": "FixedSavings",
"fixedSavingsCost": [12,22]
}, {
"name": "variableSavings",
"variableSavingsCost": [11,15]
}, {
"name": "startUpSavings",
"startUpSavingsCost": [32,21]
}, {
"name": "shutDownSavings",
"shutDownSavingsCost": [21,33]
},
],
"projectYears": 2,
"RevSev": [
{
"name": "FixedSavings",
"fixedSavingsCost": [32,23]
}, {
"name": "variableSavings",
"variableSavingsCost": [23,12]
}, {
"name": "startUpSavings",
"startUpSavingsCost": [14,32]
}, {
"name": "shutDownSavings",
"shutDownSavingsCost": [14,13]
},
],
Similarly, if projectYears is 3 then there will 3 dictionaries with 4 lists and 3 values in each of them. I was able to create the random values in the lists according to the projectYears but can't able to form separate dictionaries out of it.
My Approach:
projectLife = 3
modelOutput['RevSev'][0]['fixedSavingsCost'] = [random.randrange(1, 50, 1) for i in range(projectLife)]
modelOutput['RevSev'][0]['variableSavingsCost'] = [random.randrange(1, 50, 1) for i in range(projectLife)]
modelOutput['RevSev'][0]['startUpSavingsCost'] = [random.randrange(1, 50, 1) for i in range(projectLife)]
modelOutput['RevSev'][0]['shutDownSavingsCost'] = [random.randrange(1, 50, 1) for i in range(projectLife)]
json.dumps(modelOutput)
Here's a fairly straightforward way of doing that, given modelOutput like the above as input (or even given just the number of years you'd like to have):
years = modelOutput["projectYears"]
randoms = lambda y: np.random.randint(10, 30, y)
res = []
for year in range(1, years+1):
new_year = {
"projectYears": year,
"RevSev": [
{
"name": "FixedSavings",
"fixedSavingsCost": randoms(years)
}, {
"name": "variableSavings",
"variableSavingsCost": randoms(years)
}, {
"name": "startUpSavings",
"startUpSavingsCost": randoms(years)
}, {
"name": "shutDownSavings",
"shutDownSavingsCost": randoms(years)
}
]
}
res.append(new_year)
The result for '2' is:
[{'projectYears': 1,
'RevSev': [{'name': 'FixedSavings', 'fixedSavingsCost': array([24, 22])},
{'name': 'variableSavings', 'variableSavingsCost': array([11, 12])},
{'name': 'startUpSavings', 'startUpSavingsCost': array([27, 22])},
{'name': 'shutDownSavings', 'shutDownSavingsCost': array([25, 17])}]},
{'projectYears': 2,
'RevSev': [{'name': 'FixedSavings', 'fixedSavingsCost': array([15, 19])},
{'name': 'variableSavings', 'variableSavingsCost': array([20, 13])},
{'name': 'startUpSavings', 'startUpSavingsCost': array([26, 22])},
{'name': 'shutDownSavings', 'shutDownSavingsCost': array([24, 25])}]}]
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 3 years ago.
I'm trying to extract the values from the following json code in this format by displaying each device in a different row. Any ideas on how to do it? Thanks in advance
device1 : 232323 Completed
device2 : 345848 Completed etc
I tried the below which gives me the following output:
[{'cid': 631084346, 'data': [[{'text': 'device1'}], [{'text': '732536:Completed.'}], [{'text': '1'}]], 'id': 1750501182}, {'cid': 1891684718, 'data': [[{'text': 'device2'}], [{'text': '732536:Completed.'}], [{'text': '1'}]], 'id': 2218910703}
api_readable = api_response.json()
computer_name = str(api_readable['data']['result_sets'][0]['rows'])
# computer_name = re.sub("[{},':]", "", computer_name)
print(computer_name)
Sample Json used
{
"data": {
"max_available_age": "",
"now": "2020/01/09 22:43:58 GMT-0000",
"result_sets": [{
"age": 0,
"archived_question_id": 0,
"columns": [{
"hash": 3409330187,
"name": "Computer Name",
"type": 1
},
{
"hash": 1792443391,
"name": "Action Statuses",
"type": 1
},
{
"hash": 0,
"name": "Count",
"type": 3
}
],
"error_count": 0,
"estimated_total": 129,
"expire_seconds": 3660,
"filtered_row_count": 11,
"filtered_row_count_machines": 11,
"id": 2880628,
"issue_seconds": 0,
"item_count": 11,
"mr_passed": 129,
"mr_tested": 129,
"no_results_count": 0,
"passed": 128,
"question_id": 2880628,
"report_count": 233,
"row_count": 11,
"row_count_machines": 11,
"rows": [{
"cid": 631084346,
"data": [
[{
"text": "device1"
}],
[{
"text": "732536:Completed."
}],
[{
"text": "1"
}]
],
"id": 1750501182
},
{
"cid": 1891684718,
"data": [
[{
"text": "device2"
}],
[{
"text": "732536:Completed."
}],
[{
"text": "1"
}]
],
"id": 2218910703
}
api_readable['data']['result_sets'][0]['rows'] is a list, you can simply loop over it and print the items you want.
for row in api_readable['data']['result_sets'][0]['rows']:
print(f"{row['data'][0][0]['text']} : {row['data'][1][0]['text']}");
I found a question which is technically the same but doesn't answer my question fully and was asked 7 years ago.
The problem which I can't solve is updating a dictionary in array in document. I needed to change deck to True, but it doesn't update it. Also I didn't get any errors.
Document Structure
{
"user": 1234,
"money": 0
"inv_max": 100,
"cards": [
{
"name": "somename",
"power": 11,
"health": 10,
"rarity": 'bronze'
"deck": False,
}
],
"packs": {
"bronze": 0,
"silver": 0,
"gold": 0,
"diamond": 0,
"mythical": 0
}
}
Code which should update it (which I used)
await db.inventory.update_one(
{"user": self.user_id},
{"$set": {f"cards.{index}.deck": True}}
)
In case it's needed, I use MongoDB Atlas.
Use the positional operator $ to update:
db.inventory.updateOne(
{ "user": "1234", "cards.name": "somename"},
{ "$set": { "cards.$.deck" : "True" }} )
If you know the index you can do something like this
db.inventory.update_one(
{"user": self.user_id},
{$set: {"cards.0.deck":true}}
)
This question already has answers here:
Parsing json and searching through it
(5 answers)
Closed 5 years ago.
I have the following JSON string and I want to obtain doc_count:
import json
text = '''{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 11,
"max_score": 0,
"hits": []
},
"aggregations": {
"range": {
"buckets": [
{
"key": "2017-02-17T15:00:00.000Z-2017-02-17T16:00:00.000Z",
"from": 1487343600000,
"from_as_string": "2017-02-17T15:00:00.000Z",
"to": 1487347200000,
"to_as_string": "2017-02-17T16:00:00.000Z",
"doc_count": 2
}
]
}
}
}'''
obj = json.loads(text)
obj
I tried obj['aggregations']['range']['buckets']['doc_count'], but it does not work. How can I search through the hierarchy of this JSON file?
Because 'buckets' key contains array of element. You needs
obj['aggregations']['range']['buckets'][0]['doc_count']
You're missing the fact that the "buckets" key contains a list. You need:
obj['aggregations']['range']['buckets'][0]['doc_count']
Note the [0] after selecting the buckets key.