I have this dictionary and I need it to be formatted in a table like manner to a text file.
dictionary_lines = {'1-2': (69.18217255912117, 182.95794152905918), '2-3': (35.825144800822954, 175.40503498180715), '3-4': (37.34332738254673, 97.30771061242511), '4-5': (57.026590289091914, 97.33437880141743), '5-6': (57.23912298419586, 14.32271997820363), '6-7': (55.61382561917492, 351.4794228420951), '7-8': (41.21551406933976, 275.1365340619268), '8-1': (57.83213034291623, 272.6560961904868)}
As of right now I'm working on printing them out first before working on writing a new file. I'm stuck on how to properly format them. Here's what I got so far:
for item in dictionary_lines:
print ("{l}\t{d:<10.3f}\t{a:<10.3f}".format(l= ,d =,a = ))
I want it to be printed like this:
Lines[tab] Distances [tab] Azimuth from the South
Key 0 value1 in tuple0 Value2 in tuple0
You don't use the data from the dictionary in the format().
Also, consider using items() to iterate over key-value pairs of a dictionary as:
for key, value in dictionary_lines.items():
print ("l={}\td={:<10.3f}\ta={:<10.3f}".format(key, value[0], value[1]))
l=1-2 d=69.182 a=182.958
l=2-3 d=35.825 a=175.405
l=3-4 d=37.343 a=97.308
l=4-5 d=57.027 a=97.334
l=5-6 d=57.239 a=14.323
l=6-7 d=55.614 a=351.479
l=7-8 d=41.216 a=275.137
l=8-1 d=57.832 a=272.656
Related
I have a Python Dictionary that I converted to a NumPy array. I did this because I have some keys that show up multiple times in the dictionary (the 'Red Velvet' cupcake specifically). I'm having difficulty figuring out how to create a program that outputs a value based on a specific key inputed.
My Python Dictionary looks like this:
cupcake_dict =
{'Red Velvet': 'Princess Cupcakes',
'Vanilla': 'Vanilla Patisserie',
'Chocolate': 'Beary Good Cupcakes',
'Red Velvet': 'Bonjour Bakery'
}
So, first I converted my Python Dictionary (cupcake_dict) to an array:
result = cupcake_dict.items()
result_list = list(result)
cupcake_array = np.array(result_list)
Now, using this array, I am trying to create the program that takes an input (a key in the Python Dictionary) and searches the array (cupcake_array) to output the value (shop location). I want the program to output all the possible values. For instance, for the red velvet cupcake, there are two locations it is available at. I'm trying to get the program to print both locations for these keys.
I am struggling with, first, outputting a value from the array, and, second, outputting more than one value from the array if applicable.
Here is what I have so far (not correct):
cake_name = input("Enter Cupcake Type: ")
if cake_name in cupcake_array:
print("Cupcake Type: " + cake_name)
print("Cupcake Location: " + cupcake_array.index(cake_name))
else:
print("Cupcake not available at any locations")
Where am I going wrong? Am I approaching this correctly? Thank you!
I want to receive the average cost of a single position.
I am using the IB-insync API and using reqPositions(). The ouput is:
[Position(account='DU1675421', contract=Stock(conId=29622888, symbol='HEIA', exchange='AEB', currency='EUR', localSymbol='HEIA', tradingClass='HEIA'), position=100.0, avgCost=90.97088),
Position(account='DU1675421', contract=Future(conId=176791153, symbol='N225M', lastTradeDateOrContractMonth='20191212', multiplier='100', currency='JPY', localSymbol='164120019', tradingClass='NK225M'), position=1.0, avgCost=2284540.0)]
I would like to have the avgcost of 1 position. How would I do this?
b = ib.reqPositions()
while ib.sleep(0.5):
plb = b
print (plb)
b.avgCost() doesn't work.
It looks like reqPositions is returning a list of namedtuples.
To access an element in the namedtuple you would need to iterate over the list, e.g.
for position in b:
print(position.avgCost)
I'm trying to put a for loop inside of a dict. (See my code bellow)
tempdict["data"] = {
"id": words[0],
for j in range(1, 100):
tempdict[fieldnames[j]] = words[j]
}
So, I'm reading out of a CSV file and converting it to JSON. (This is to automate a process at work)
Not sure if there is anything else to add, just ask if you need to know more.
I would appreciate any help I can get :)
so, extra context:
I'm trying to map the value from the CSV file to the dict with the key as one of the fieldnames (See fieldnames bellow)
fieldnames = ["id", "subscriber-A-01", "subscriber-A-02", "subscriber-A-03", "subscriber-A-04", "subscriber-A-05", "subscriber-A-06", "subscriber-A-07", "subscriber-A-08", "subscriber-A-09", "subscriber-A-10", "subscriber-B-01", "subscriber-B-02", "subscriber-B-03", "subscriber-B-04", "subscriber-B-05", "subscriber-B-06", "subscriber-B-07", "subscriber-B-08", "subscriber-B-09", "subscriber-B-10", "subscriber-C-01", "subscriber-C-02", "subscriber-C-03", "subscriber-C-04", "subscriber-C-05", "subscriber-C-06", "subscriber-C-07", "subscriber-C-08", "subscriber-C-09", "subscriber-C-10", "subscriber-D-01", "subscriber-D-02", "subscriber-D-03", "subscriber-D-04", "subscriber-D-05", "subscriber-D-06", "subscriber-D-07", "subscriber-D-08", "subscriber-D-09", "subscriber-D-10", "subscriber-E-01", "subscriber-E-02", "subscriber-E-03", "subscriber-E-04", "subscriber-E-05", "subscriber-E-06", "subscriber-E-07", "subscriber-E-08", "subscriber-E-09", "subscriber-E-10", "subscriber-F-01", "subscriber-F-02", "subscriber-F-03", "subscriber-F-04", "subscriber-F-05", "subscriber-F-06", "subscriber-F-07", "subscriber-F-08", "subscriber-F-09", "subscriber-F-10", "subscriber-G-01", "subscriber-G-02", "subscriber-G-03", "subscriber-G-04", "subscriber-G-05", "subscriber-G-06", "subscriber-G-07", "subscriber-G-08", "subscriber-G-09", "subscriber-G-10", "subscriber-H-01", "subscriber-H-02", "subscriber-H-03", "subscriber-H-04", "subscriber-H-05", "subscriber-H-06", "subscriber-H-07", "subscriber-H-08", "subscriber-H-09", "subscriber-H-10", "subscriber-I-01", "subscriber-I-02", "subscriber-I-03", "subscriber-I-04", "subscriber-I-05", "subscriber-I-06", "subscriber-I-07", "subscriber-I-08", "subscriber-I-09", "subscriber-I-10", "subscriber-J-01", "subscriber-J-02", "subscriber-J-03", "subscriber-J-04", "subscriber-J-05", "subscriber-J-06", "subscriber-J-07", "subscriber-J-08", "subscriber-J-09", "subscriber-J-10", "DISPLAY_TYPE", "stationCode"]
So, from subscriber-A-1 to subscriber-J-10 should be mapped to value 1 to 100 of the CSV file.
Update
This is how I made it work.
tempdict["data"] = dict(zip(fieldnames[1:100], words[1:100]))
tempdict["data"].update({"DISPLAY_TYPE": words[102]})
Thank you all for the help!
You can pair the sliced list of keys and the sliced list of values with zip and pass the zipped pairs to the dict constructor to build the desired dict instead:
tempdict['data'] = dict(zip(fieldnames[:101], words[:101]))
Please I need some help again.
I have a big data base file (let's call it db.csv) containing many informations.
Simplified database file to illustrate:
I run usearch61 -cluster_fast on my genes sequences in order to cluster them.
I obtained a file named 'clusters.uc'. I opened it as csv then I made a code to create a dictionary (let's say dict_1) to have my cluster number as keys and my gene_id (VFG...) as values.
Here is an example of what I made then stored in a file: dict_1
0 ['VFG003386', 'VFG034084', 'VFG003381']
1 ['VFG000838', 'VFG000630', 'VFG035932', 'VFG000636']
2 ['VFG018349', 'VFG018485', 'VFG043567']
...
14471 ['VFG015743', 'VFG002143']
So far so good. Then using db.csv I made another dictionary (dict_2) were gene_id (VFG...) are keys and VF_Accession (IA... or CVF.. or VF...) are values, illustration: dict_2
VFG044259 IA027
VFG044258 IA027
VFG011941 CVF397
VFG012016 CVF399
...
What I want in the end is to have for each VF_Accession the numbers of cluster groups, illustration:
IA027 [0,5,6,8]
CVF399 [15, 1025, 1562, 1712]
...
So I guess since I'm still a beginner in coding that I need to create a code that compare values from dict_1(VFG...) to keys from dict_2(VFG...). If they match put VF_Accession as a key with all cluster numbers as values. Since VF_Accession are keys they can't have duplicate I need a dictionary of list. I guess I can do that because I made it for dict_1. But my problem is that I can't figure out a way to compare values from dict_1 to keys from dict_2 and put to each VF_Accession a cluster number. Please help me.
First, let's give your dictionaries some better names then dict_1, dict_2, ... that makes it easier to work with them and to remember what they contain.
You first created a dictionary that has cluster numbers as keys and gene_ids (VFG...) as values:
cluster_nr_to_gene_ids = {0: ['VFG003386', 'VFG034084', 'VFG003381', 'VFG044259'],
1: ['VFG000838', 'VFG000630', 'VFG035932', 'VFG000636'],
2: ['VFG018349', 'VFG018485', 'VFG043567', 'VFG012016'],
5: ['VFG011941'],
7949: ['VFG003386'],
14471: ['VFG015743', 'VFG002143', 'VFG012016']}
And you also have another dictionary where gene_ids are keys and VF_Accessions (IA... or CVF.. or VF...) are values:
gene_id_to_vf_accession = {'VFG044259': 'IA027',
'VFG044258': 'IA027',
'VFG011941': 'CVF397',
'VFG012016': 'CVF399',
'VFG000676': 'VF0142',
'VFG002231': 'VF0369',
'VFG003386': 'CVF051'}
And we want to create a dictionary where each VF_Accession key has as value the numbers of cluster groups: vf_accession_to_cluster_groups.
We also note that a VF Accession belongs to multiple gene IDs (for example: the VF Accession IA027 has both the VFG044259 and the VFG044258 gene IDs.
So we use defaultdict to make a dictionary with VF Accession as key and a list of gene IDs as value
from collections import defaultdict
vf_accession_to_gene_ids = defaultdict(list)
for gene_id, vf_accession in gene_id_to_vf_accession.items():
vf_accession_to_gene_ids[vf_accession].append(gene_id)
For the sample data I posted above, vf_accession_to_gene_ids now looks like:
defaultdict(<class 'list'>, {'VF0142': ['VFG000676'],
'CVF051': ['VFG003386'],
'IA027': ['VFG044258', 'VFG044259'],
'CVF399': ['VFG012016'],
'CVF397': ['VFG011941'],
'VF0369': ['VFG002231']})
Now we can loop over each VF Accession and look up its list of gene IDs. Then, for each gene ID, we loop over every cluster and see if the gene ID is present there:
vf_accession_to_cluster_groups = {}
for vf_accession in vf_accession_to_gene_ids:
gene_ids = vf_accession_to_gene_ids[vf_accession]
cluster_group = []
for gene_id in gene_ids:
for cluster_nr in cluster_nr_to_gene_ids:
if gene_id in cluster_nr_to_gene_ids[cluster_nr]:
cluster_group.append(cluster_nr)
vf_accession_to_cluster_groups[vf_accession] = cluster_group
The end result for the above sample data now is:
{'VF0142': [],
'CVF051': [0, 7949],
'IA027': [0],
'CVF399': [2, 14471],
'CVF397': [5],
'VF0369': []}
Caveat: I don't do much Python development, so there's likely a better way to do this. You can first map your VFG... gene_ids to their cluster numbers, and then use that to process the second dictionary:
from collections import defaultdict
import sys
import ast
# see https://stackoverflow.com/questions/960733/python-creating-a-dictionary-of-lists
vfg_cluster_map = defaultdict(list)
# map all of the vfg... keys to their cluster numbers first
with open(sys.argv[1], 'r') as dict_1:
for line in dict_1:
# split the line at the first space to separate the cluster number and gene ID list
# e.g. after splitting the line "0 ['VFG003386', 'VFG034084', 'VFG003381']",
# cluster_group_num holds "0", and vfg_list holds "['VFG003386', 'VFG034084', 'VFG003381']"
cluster_group_num, vfg_list = line.strip().split(' ', 1)
cluster_group_num = int(cluster_group_num)
# convert "['VFG...', 'VFG...']" from a string to an actual list
vfg_list = ast.literal_eval(vfg_list)
for vfg in vfg_list:
vfg_cluster_map[vfg].append(cluster_group_num)
# you now have a dictionary mapping gene IDs to the clusters they
# appear in, e.g
# {'VFG003386': [0],
# 'VFG034084': [0],
# ...}
# you can look in that dictionary to find the cluster numbers corresponding
# to your vfg... keys in dict_2 and add them to the list for that vf_accession
vf_accession_cluster_map = defaultdict(list)
with open(sys.argv[2], 'r') as dict_2:
for line in dict_2:
vfg, vf_accession = line.strip().split(' ')
# add the list of cluster numbers corresponding to this vfg... to
# the list of cluster numbers corresponding to this vf_accession
vf_accession_cluster_map[vf_accession].extend(vfg_cluster_map[vfg])
for vf_accession, cluster_list in vf_accession_cluster_map.items():
print vf_accession + ' ' + str(cluster_list)
Then save the above script and invoke it like python <script name> dict1_file dict2_file > output (or you could write the strings to a file instead of printing them and redirecting).
EDIT: After looking at #BioGeek's answer, I should note that it would make more sense to process this all in one shot than to create dict_1 and dict_2 files, read them in, parse the lines back into numbers and lists, etc. If you don't need to write the dictionaries to a file first, then you can just add your other code to the script and use the dictionaries directly.
for line in open('transactions.dat','r'):
item=line.rstrip('\n')
item=item.split(',')
custid=item[2]
amt=item[4]
if custid in cust1:
a=cust1[custid]
b=amt
c=(a)+(b)
print(cust1[custid]+" : "+a+" :"+b+":"+c)
break
else:
cust1[custid]=amt
Output:
85.91 : 85.91 :85.91:85.9185.91
Well above is my code what I want is
when I read from a file I want to add the customer amount with same
id.
Secondly there should not be repetition of customer id in my
dictionary.
so I am trying to add customer amount which is c but it gives me appended string instead of adding the two. You can see in the last part of my output which is value of c. So how do I add the values.
Sample transaction data:
109400182,2016-09-10,119257029,1094,40.29
109400183,2016-09-10,119257029,1094,9.99
377700146,2016-09-10,119257029,3777,49.37
276900142,2016-09-10,135127654,2769,23.31
276900143,2016-09-10,135127654,2769,25.58
You reading strings, instead of floats, from the file. Use this amt=float(item[4]) to convert strings representing numbers to floats, and then print(str(cust1[custid])+" : "+str(a)+" :"+str(b)+":"+str(c)) to print out.
Your code may need lots of refactor, but in a nutshell and if I understand what you are trying to do you could do
c = float(a) + float(b)
and that should work.