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
Related
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.
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 a list of named tuple as below
record = [({
"first_name":"nadbor",
"last_name":"drozd",
"occupation":"data scientist",
"markingAgentUsed":[
{
"consumableLabelCode":"L",
"amountUsed":{
"amount" : 100,
"unit": "litre"
}
},
{
"consumableLabelCode":"Y",
"amountUsed":{
"amount" : 300,
"unit": "mililitre"
}
},
{
"consumableLabelCode":"0",
"amountUsed":{
"amount" : 999,
"unit": "gallon"
}
}
]
})]
[{'first_name': 'nadbor', 'last_name': 'drozd', 'occupation': 'data scientist', 'markingAgentUsed': [{'consumableLabelCode': 'L', 'amountUsed': {'amount': 100, 'unit': 'litre'}}, {'consumableLabelCode': 'Y', 'amountUsed': {'amount': 300, 'unit': 'mililitre'}}, {'consumableLabelCode': '0', 'amountUsed': {'amount': 999, 'unit': 'gallon'}}]}]
I want to extract the values based on a input parameter of LabelCode, I want to extract the two values amount and unit.
for example if i pass O, I should get 999 and gallon as output.
record = [({
"first_name":"nadbor",
"last_name":"drozd",
"occupation":"data scientist",
"markingAgentUsed":[
{
"consumableLabelCode":"L",
"amountUsed":{
"amount" : 100,
"unit": "litre"
}
},
{
"consumableLabelCode":"Y",
"amountUsed":{
"amount" : 300,
"unit": "mililitre"
}
},
{
"consumableLabelCode":"0",
"amountUsed":{
"amount" : 999,
"unit": "gallon"
}
}
]
})]
userKey = '0'
for entry in record[0]['markingAgentUsed']:
if entry['consumableLabelCode'] == userKey:
print("Amount - {}".format(entry['amountUsed']['amount']) )
print("Units - {}".format(entry['amountUsed']['unit']) )
It is all about understanding the nesting of the data structure (which is not a named tuple, but a list of tuples of dictionaries with a list of dictionaries of which some keys are dictionaries themselves :-/ Few! This piece of code extracts what you ask for:
inp = '0'
for ma in record[0]['markingAgentUsed']:
if ma['consumableLabelCode'] == inp:
print(ma['amountUsed']['amount'], ma['amountUsed']['unit'])
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])}]}]
There is a dictionary initialized, serializer provides some data and adding to a nested array is made by iterating list of items:
list = {"shopping_list": []}
item = {}
count = 0
stuff = json.loads(serializer.data["stuff_file"])
for s in stuff:
item["level"] = count
item["position"] = count * 10
item["item_name"] = s["name"]
list["shopping_list"].append(item)
count += 1
But instead of receiving a list of unique items (expected the append method to do that), I get the list with proper count of items, but all previous ones are overwritten by the most recent one, like:
{
"shopping_list": [
{
"level": 2,
"position": 20,
"item_name": "Bronze Badge"
},
{
"level": 2,
"position": 20,
"item_name": "Bronze Badge"
},
{
"level": 2,
"position": 20,
"item_name": "Bronze Badge"
}
]
}
How should I write to the list to have all of the items unique, e.g.:
{
"shopping_list": [
{
"level": 0,
"position": 0,
"item_name": "Gold Badge"
},
{
"level": 1,
"position": 10,
"item_name": "Silver Badge"
},
{
"level": 2,
"position": 20,
"item_name": "Bronze Badge"
}
]
}
?
Instead of creating the variable outside the loop, create item inside it:
list = {"shopping_list": []}
count = 0
stuff = [{"name": "Gold Badge"}, {"name": "Silver Badge"}, {"name": "Bronze Badge"}]
for s in stuff:
item = {}
item["level"] = count
item["position"] = count * 10
item["item_name"] = s["name"]
list["shopping_list"].append(item)
count += 1
print(list)
Output:
{'shopping_list': [{'level': 0, 'position': 0, 'item_name': 'Gold Badge'}, {'level': 1, 'position': 10, 'item_name': 'Silver Badge'},{'level': 2, 'position': 20, 'item_name': 'Bronze Badge'}]}
As #DeepSpace pointed out, you can also use a dictionary literal:
for s in stuff:
list["shopping_list"].append({'level': count, 'position': count * 10, 'item_name': s['name']})
count += 1
In fact, you could get rid of the count variable and do this as well:
for count, s in enumerate(stuff):
list["shopping_list"].append({'level': count, 'position': count * 10, 'item_name': s['name']})