This question already has answers here:
Access nested key-values in Python dictionary
(2 answers)
Closed 11 months ago.
I am currently doing the 100 days of code course on Udemy, and I have been given this code.
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
How do I call the 'cost' part?
You can use menu['<name of item you want to get cost for>']['cost'].
For example, print(menu['espresso']['cost']) should output 1.5.
Related
This question already has answers here:
Iterate the keys and values from the dictionary
(3 answers)
Closed 18 days ago.
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
I can only print the first dic (coffee names) keys, but for some reason I cannot reach the costs...
for item in MENU:
for item2,cost in item:
print(f" {item} {cost} ")
You can't magically fetch a dictionary value without passing the key name ('cost' in your case). Try this as an example:
for item, data in MENU.items():
print(f"Item {item}, cost: {data['cost']}")
this should print
Item espresso, cost: 1.5
Item latte, cost: 2.5
Item cappuccino, cost: 3.0
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)
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])}]}]
I am trying to deep sort a list of json of list (and so on..which can go recursively nested) where json can have duplicate keys, and without a specific key in the json to sort on.
Input:
{"payload": [
{
"a": {
"aa": [
{
"aa12": {
"aaa23": 230,
"aaa21": 210,
"aaa.something": "yes"
}
},
{
"aa11": {
"aaa12": 120,
"aaa11": 110
}
},
{
"aa13": {
"aaa35": 350,
"aaa32": 320,
"aaa.someattr": "true"
}
}
],
"aa": [
{
"aa12": {
"aaa22": 22,
"aaa21": 21
}
},
{
"aa10": {
"aaa03": 3,
"aaa01": 1
}
},
{
"aa13": {
"aaa33": 33,
"aaa32": 32
}
},
{
"aa1": "aab"
}
],
"ac": [
"ac3",
"ac1",
"ac2"
]
}
},
{
"b": {
"bb": [
"bb4",
"bb2",
"bb3",
"bb1"
]
}
}
]}
Expected Output:
{"payload": [
{
"a": {
"aa": [
{
"aa1": "aab"
},
{
"aa10": {
"aaa01": 1,
"aaa03": 3
}
},
{
"aa12": {
"aaa21": 21,
"aaa22": 22
}
},
{
"aa13": {
"aaa32": 32,
"aaa33": 33
}
}
],
"aa": [
{
"aa11": {
"aaa11": 110,
"aaa12": 120
}
},
{
"aa12": {
"aaa.something": "yes"
"aaa21": 210,
"aaa23": 230
}
},
{
"aa13": {
"aaa.someattr": "true",
"aaa32": 320,
"aaa35": 350
}
}
],
"ac": [
"ac1",
"ac2",
"ac3"
]
}
},
{
"b": {
"bb": [
"bb1",
"bb2",
"bb3",
"bb4"
]
}
}
]}
I have tried using the below recursive method:
ls = {'payload': [{'a': {'aa': [{'aa12': {'aaa23': 230, 'aaa21': 210}}, {'aa11': {'aaa12': 120, 'aaa11': 110}}, {'aa13': {'aaa35': 350, 'aaa32': 320}}], 'ac': ['ac3', 'ac1', 'ac2'], 'aa': [{'aa12': {'aaa22': 22, 'aaa21': 21}}, {'aa10': {'aaa03': 3, 'aaa01': 1}}, {'aa13': {'aaa33': 33, 'aaa32': 32}}, {'aa1': 'aab'}]}}, {'b': {'bb': ['bb4', 'bb2', 'bb3', 'bb1']}}]}
output = sorted_deep(ls)
print(output)
def sorted_deep(d):
if isinstance(d,list):
return sorted(sorted_deep(v) for v in d)
if isinstance(d,dict):
return {k: sorted_deep(d[k]) for k in sorted(d)}
return d
But this ain't working. It overrides the duplicate key's value with the last found value when it sorts. Since the duplicate key can be any string, we can't iterate by specifying the key name.
I'm looking for a generic solution which sorts any given complex list of json's - with nested list's/json's.
My end goal is to deep match 2 such JSON's to find the differences.
Consider using sorted()
sorted(paymentsByAgreeement[agreement['agreementId']],key=lambda i:
(i['eventDate'],i['id']))
read about sorted and lambda here https://wiki.python.org/moin/HowTo/Sorting
with lambda, you can access child elements to go deeper you may need a for and another lambda with sorted
I want to count the number of elements in an array using python and pymongo. Here is the data.
{
"_id": 5,
"type": "Student",
"Applicates": [
{
"appId": 100,
"School": "dfgdfgd",
"Name": "tony",
"URL": "www.url.com",
"Time": "5/5/5-6/6/6",
"Research": "dfgdfg",
"Budge": 5000,
"citizenship": "us",
"Major": "csc",
"preAwards": "None",
"Advisor": "dfgdfg",
"Evaluators": [
{
"abstractScore": 10,
"goalsObjectivesScore": 20,
"evalNum": 1
},
{
"abstractScore": 30,
"goalsObjectivesScore": 40,
"evalNum": 2
},
{
"abstractScore": 50,
"goalsObjectivesScore": 60,
"evalNum": 3
}
]
},
{
"appId": 101,
"School": "dvdu",
"Name": "jessy",
"URL": "www.url.com",
"Time": "4/4/4-6/6/6",
"Research": "dfgdfg",
"Budge": 7500,
"citizenship": "us",
"Major": "dfgdfg",
"preAwards": "dfgfd",
"Advisor": "dfgdfg",
"Evaluators": [
{
"abstractScore": 70,
"goalsObjectivesScore": 80,
"evalNum": 1
},
{
"abstractScore": 90,
"goalsObjectivesScore": 100,
"evalNum": 2
}
]
}
]}
So I want to get the size of the Evaluators array. {"appId" : 100} would give 3 and {"appId" : 101} would give 2. I have been playing around with $size but cant seem to get it.
Queries return documents. No query will return the size of the Evaluators array in the array element with "appId" : 100`. But the following awkwardly formatted expression will so what you want:
len(coll.find_one(
{ "Applicates.appId" : 100 },
{ "Applicates.$.Evaluators" : 1 }
)["Applicates"][0]["Evaluators"])
where coll is the Collection object.
With this syntax { $size: <expression> } you can count number of items in an array. See here for more > $size
One approach would be to loop through your array, and then on each iteration use len() on that dict's Evaluators property.
for obj in Applicates:
count = len(obj['Evaluators'])