Printing out dictionaries in Python - python

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])

Related

Iterate over two dict, match on key values and return concatenated values

I am iterating over two dictionaries and when I find a match on keys I concatenate values from both dictionaries and create a url and store the results in a new list.
database_dict is static and will never change. However the second dictionary cross_ref_dict is based on values from a file that I am parsing.
So in a nutshell the database_dict will always have more values then the cross_ref_dict.
Below you will find my current solution, which works fine when the amount of elements in both dictionaries is the same. But when they are different I receive an empty list. How do I handle this situation and return concatenated values only for those that are found in database_dict?
I would only like to concatenate the values if the keys match, if there is no match or no value is found I would like that nothing is returned.
database_dict = { 'CLO' : 'https://www.ebi.ac.uk/ols/ontologies/clo/terms?iri=http://purl.obolibrary.org/obo/',
'EFO' : ' https://www.ebi.ac.uk/efo/',
'ArrayExpress' : 'https://www.ebi.ac.uk/arrayexpress/experiments/',
'ATCC' : 'https://www.atcc.org/Products/All/', # + .aspx
'BioSample' : 'https://www.ncbi.nlm.nih.gov/biosample/?term=',
'CCLE' : 'https://portals.broadinstitute.org/ccle/page?cell_line=',
'Cell_Model_Passport' : 'https://cellmodelpassports.sanger.ac.uk/passports/',
'ChEMBL-Cells' : 'https://www.ebi.ac.uk/chembldb/cell/inspect/',
'ChEMBL-Targets' : 'https://www.ebi.ac.uk/chembldb/target/inspect/',
'Cosmic' : 'https://cancer.sanger.ac.uk/cosmic/sample/overview?id=',
'Cosmic-CLP' : 'https://cancer.sanger.ac.uk/cell_lines/sample/overview?id=',
'DepMap' : 'https://depmap.org/portal/cell_line/ACH-000830',
'GDSC' : 'https://www.cancerrxgene.org/translation/CellLine/',
'GEO' : 'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=',
'IARC_TP53' : 'https://p53.iarc.fr/CellLines.aspx',
'IGRhCellID' : 'http://igrcid.ibms.sinica.edu.tw/cgi-bin/cell_line_view.cgi?cl_name=',
'KCLB' : 'https://cellbank.snu.ac.kr/english/sub/catalog.php?page=detail&CatNo=59&strQ=', # + &submit1=Find+it
'LiGeA' : 'http://hpc-bioinformatics.cineca.it/fusion/cell_line/',
'LINCS_LDP' : 'http://lincsportal.ccs.miami.edu/cells/#/view/',
'PharmacoDB' : 'https://pharmacodb.ca/cell_lines/',
'PRIDE' : 'https://www.ebi.ac.uk/pride/archive/projects/',
'Wikidata' : 'https://www.wikidata.org/wiki/',
'test' : 'test',
'test2' : 'test2'
}
cross_ref_dict = {'CLO': 'CLO_0007996', 'EFO': 'EFO_0002253', 'ArrayExpress': 'E-MTAB-3610', 'ATCC': 'CRL-5871', 'BioSample': 'SAMN10988000', 'CCLE': 'NCIH1436_LUNG', 'Cell_Model_Passport': 'SIDM00697', 'ChEMBL-Cells': 'CHEMBL3308893', 'ChEMBL-Targets': 'CHEMBL2366205', 'Cosmic': '2125229', 'Cosmic-CLP': '908469', 'DepMap': 'ACH-000830', 'GDSC': '908469', 'GEO': 'GSM1682805', 'IARC_TP53': '21539', 'IGRhCellID': 'NCIH1436', 'KCLB': '91436', 'LiGeA': 'CCLE_790', 'LINCS_LDP': 'LCL-1838', 'PharmacoDB': 'NCIH1436_1017_2019', 'PRIDE': 'PXD011896', 'Wikidata': 'Q54907807'}
# if the keys in dicts match, concatenate the base link from `database_dict` with the appropriate
value from `cross_ref_dict`
key_values['Cross-ref'] = [(str(database_dict.get(k, 0))+str(cross_ref_dict.get(k, 0))) for k
in set(database_dict.keys()) | set(cross_ref_dict.keys()) if
database_dict.keys() == cross_ref_dict.keys()]
You can find the intersection of the keys, and then simply iterate over it.
something like:
set(cross_ref_dict.keys()).intersection(set(database_dict.keys()))
This will keep only the keys that are mutual to both dictionaries, regardless of the size of each one of them. Then you can simply iterate on the intersected keys with no worries.
So using your logic:
[database_dict.get(k) + cross_ref_dict.get(k) for k in set(cross_ref_dict.keys()).intersection(set(database_dict.keys()))]
# ['https://www.ncbi.nlm.nih.gov/biosample/?term=SAMN10988000', 'https://www.ebi.ac.uk/ols/ontologies/clo/terms?iri=http://purl.obolibrary.org/obo/CLO_0007996', 'https://www.ebi.ac.uk/chembldb/target/inspect/CHEMBL2366205', 'https://cancer.sanger.ac.uk/cell_lines/sample/overview?id=908469', 'https://www.ebi.ac.uk/pride/archive/projects/PXD011896', 'https://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-3610', 'https://cancer.sanger.ac.uk/cosmic/sample/overview?id=2125229', 'http://lincsportal.ccs.miami.edu/cells/#/view/LCL-1838', 'https://www.wikidata.org/wiki/Q54907807', 'https://depmap.org/portal/cell_line/ACH-000830ACH-000830', 'https://www.atcc.org/Products/All/CRL-5871', 'http://hpc-bioinformatics.cineca.it/fusion/cell_line/CCLE_790', 'https://p53.iarc.fr/CellLines.aspx21539', 'http://igrcid.ibms.sinica.edu.tw/cgi-bin/cell_line_view.cgi?cl_name=NCIH1436', 'https://cellmodelpassports.sanger.ac.uk/passports/SIDM00697', 'https://www.cancerrxgene.org/translation/CellLine/908469', 'https://cellbank.snu.ac.kr/english/sub/catalog.php?page=detail&CatNo=59&strQ=91436', 'https://portals.broadinstitute.org/ccle/page?cell_line=NCIH1436_LUNG', 'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM1682805', 'https://www.ebi.ac.uk/chembldb/cell/inspect/CHEMBL3308893', 'https://pharmacodb.ca/cell_lines/NCIH1436_1017_2019', ' https://www.ebi.ac.uk/efo/EFO_0002253']
use a dictionary comprehension
results={key:data for (key,data) in database_dict.items() if key in cross_ref_dict.keys()}
print(results)

Indexing Dict with Multiple values at one key

I'm new to python and I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values(list) associated with it.
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
Let's say I want to iterate through values and print out the value if it's equal to 'DOG'. Do Values, Key pairs have a specific index associated with the position of Values?
I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.
You can perform the following (comments included):
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for keys, values in d.items(): #Will allow you to reference the key and value pair
for item in values: #Will iterate through the list containing the animals
if item == "DOG":
print(item)
print(values.index(item)) #will tell you the index of "DOG" in the list.
So maybe this will help:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
print(animal)
Update -What if I want to compare the string to see if they're equal or not... let say if the value at the first index is equal to the value at the second index.
You can use this:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
if list(d.keys())[0] == list(d.keys())[1]:
print("Equal")
else: print("Unequal")
Keys and values in a dictionary are indexed by key and do not have a fixed index like in lists.
However, you can leverage the use of 'OrderedDict' to give an indexing scheme to your dictionaries. It is seldom used, but handy.
That being said, dictionaries in python3.6 are insertion ordered :
More on that here :
Are dictionaries ordered in Python 3.6+?
d = {'animal': ['cat', 'dog', 'kangaroo', 'monkey'], 'flower': ['hibiscus', 'sunflower', 'rose']}
for key, value in d.items():
for element in value:
if element is 'dog':
print(value)
does this help? or, you want to print index of key in dictionary?

How to properly create a dictionary in Python

I am trying to create a dictionary in a function but I don't know for which reason I got this:
MONdic = {"mama"}
print MONdic
What I get as a result is :
set(['mama'])
Any help ?
dict is based on key value pairs (You have created a set)
d = {'key':'val'}
By default, if you pass an element or list of elements to {}, it will create a set.
But if you try passing key value pairs to {}, it will create a dictionary.
MONdic = {"key":"value"}, then the value of MONdic will be {"key":"value"}
dictionary must has keys and values
like:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
check https://www.w3schools.com/python/python_dictionaries.asp
for accessing it, changing values, loop it ..
But the problem is that I have a second dictionary that should merge with MONdic as in this example:
for key, value in results.items():
MONdic[key].extend(value)
To be able to merge these two dictionaries, they need to have the same keys. The values of MONdic should be empty in the beginning and I don't want to receive these kind of results if I do so :
MONdic = {"mama":[]}
for key, value in results.items():
MONdic[key].extend(value)
>>>> {"mama":[[1,2,5,9]]}

Finding Dictionary Key with index number

I am attempting to get the Keys in a dictionary
My current method of doing this is using a for loop to iterate through the dictionary. The value of each key is unknown as they are randomly generated.
Dictionary Format for _GENOME[xx][yy].WEIGHTS is {(0,0) : 2, (1,3) : 3}
for i in _GENOME[xx][yy].WEIGHTS:
print(xx,yy,_GENOME[xx][yy].WEIGHTS[i])
I understand my solution will need to use the .index() function. However i can't find a way to implement this into my system.
My hope is to print out each variable of the key tuple separately.
Does this help?
for key, value in d.items():
print (("Key - (#1:%s, #2:%s), value - %s ") %(key[0], key[1], value))
where d is whatever dictionary object you have (_GENOME[xx][yy].WEIGHTS ?)

Replace a specific dictionary entry

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

Categories