For my assignment I'm required to use file management in order to access information about the price/stock of certain items.
I'm currently using a dict like this
stock = {"Bread" : 27,
"Car" : 1,
"Banana" : 3000}
How would I go about to change the number of bananas in stock for instance?
stock["Banana"] = new_value should do it.
You can access value using key in dictionary , so you can go like this -
stock['Banana']=23 // any desired number
Related
say I have a dictionary like this:
profile = {'Person':{'name':['John'], 'Description':['smart']}}
I am looking for a piece of code that searches for 'John', and 'Description', but doesn't know where they are in the nested dictionary. I also want to the code to print something like this:
John is located in the value of profile['Person']
Description is located in the key of profile['Person']
How can I do that? Any help will be appreciated. Thank you
Learn how to iterate through a nested dictionary. In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Indexing [ ] is used to access an element of a nested dictionary
profile = {'Person':{'name':['John'], 'Description':['smart']},'Person1':{'name':['John1'], 'Description':['smart1']}}
for p_id, p_info in profile.items():
for key in p_info:
if p_info[key][0] == "John":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
if p_info[key][0] == "smart":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
I am using the python code below to extract some values from an excel spreadsheet and then push them to an html page for further processing. I would like to modify the code below so that I can add additional values against each task, any help
the code below does spit out the following:
{'line items': {'AMS Upgrade': '30667', 'BMS works':
'35722'}}
How can I revise the code below so that I can add 2 more values against each task i.e. AMS Upgrade and BMS works
and get the likes of (note the structure below could be wrong)
{'line items': {'AMS Upgrade': {'30667','100%', '25799'}},{'BMS works':
{'10667','10%', '3572'}} }
Code:
book = xlrd.open_workbook("Example - supporting doc.xls")
first_sheet = book.sheet_by_index(-1)
nested_dict = {}
nested_dict["line items"] = {}
for i in range(21,175):
Line_items = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=8)
if str(Line_items[0].value) and str(Line_items[1].value):
if not Line_items[5].value ==0 :
nested_dict["line items"].update({str(Line_items[0].value) : str(Line_items[1].value)})
print nested_dict
print json.dumps(nested_dict)
*** as requested see excel extract below
In Python, each key of a dict can only be associated with a single value. However that single value can be a dict, list, set, etc that holds many values.
You will need to decide the type to use for the value associated with the 'AMS Upgrade' key, if you want it to hold multiple values like '30667','10%', '222'.
Note: what you have written:
{'30667','100%', '25799'}
Is a set literal in Python.
I have a Python dictionary as below:
Mail_Dict = {
MailList0 : CodeList0,
MailList1 : CodeList1,
MailList2 : CodeList2,
MailList3 : CodeList3,
MailList4 : CodeList4
}
The issue is when one of the MailLists have values that are the same as another MailList (ie: MailList0 = 'someone#email.com' and also MailList1 = 'someone#email.com'), the keys are treated as equal and CodeList0 gets overwritten by CodeList1, also making my dictionary shorter in the process.
Is there anyway to keep these separate? I would think that the same logic for below:
a=1
b=1
saving to separate memory addresses and being different from:
a=b=1
would apply here, but I guess that isn't the case =(
Thanks in advance.
If you want to create both the values of the same key in the dictionary, one solution would be to add the old value to a list and append the new value to the list.
Mail_Dict = {
MailList0 : CodeList0,
MailList2 : CodeList2,
MailList3 : CodeList3,
MailList4 : CodeList4
}
Now if you want to add MailList1 (which has the same value as MailList0) to the dictionary, check if MailList1 already is a list. if it is not a list make it into a list and then append the new value.
if(MailList1 in Mail_Dict):
if (isinstance(Mail_Dict[MailList1],list)==False):
Mail_Dict[MailList1] = [Mail_Dict[MailList1]
Mail_Dict[MailList1].append(codeList1)
Eg:
ECE_student_list = [['section-1', [["sai",'science'], ["rama",'maths']]],
['section-2', [["seetha",'science'], ["ravana",'maths']]]]
I have to print student name and subject by passing key as section name.
for Eg : if the key is 'section-1' first student then it should print "sai",'science'
second student ,then it should print "rama",'maths'
please share the logic in python.
Won't share the code directly. That you have to learn and experiment on your own. Although I can tell you what you can expect as your output.
You can create a dictionary in python and add section-1, section-2 as the keys and the list of students as value for each key.
Your dictionary structure will be something like this:
{
'section-1' : [
{'sai':'science'},
{'rama':'math'}
],
'section-2':[
{'sai':'science'},
{'rama':'math'}
]
}
I am learning programming in Python. My task is to create two dictionaries with these values:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
I am tasked to print out things about the dictionary in this format: I was supposed to use a FOR loop to access the data.
apple
price: 2
stock: 0
The instructions said that since the two dictionaries have the same "keys" that I could access both of them at the same time. However I don't know what this means. Learning Python so far has been a breeze, but this has me stumped.
Both dictionaries have a 'banana' key, both have a 'apple' key, etc. Presumably that means you can loop over the keys of one and rely on the same key being present in the other:
for key in stock:
print key, stock[key], prices[key]
The above code will print the keys in stock, adding the value from that dictionary and also looking up the value in prices. If prices does not have the same keys, the code would fail with a KeyError.
I'll leave the actual output up to you, but now your problem is reduced to calculating the stock value.
A dictionary is a list of "key: value" pairs. When you want to get the value from a dictionary you specify the key which points to that value. Since both dictionaries you mentioned have the same keys (e.g., apple, banana), you can use the same key to get values out of both of them.
In order to get all of the keys in a dictionary, you can use the "keys" function. So the code you want is:
for key in prices.keys():
print(key)
print("prices: %s" % prices[key])
print("stock: %s" % stock[key])