I have written a code that looks through a transaction list and sees if a company is buying or selling and converts the value to USD and then returns it. the problem is my original list looks like this:
[['Acer', 481242.74], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]
and when i run my code it iterates through about 100 transactions, and after each transaction returns a sample like the following:
['Acer', 21439.6892]
now my problem is i want to update the value in the original list with this new value so that it would still have the company name but the two values behind it would be added and the new value would appear in the original list for the next iteration. so 481242.74+21439.6892=502682.4292 so the new original list would look like the following with the acer value updated
[['Acer',502682.4292 ], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]
You should use a dictionary instead to order your companies
d ={'Acer': 481242.74,'Beko': 966071.86, 'Cemex': 187242.16, 'Datsun': 748502.91, 'Equifax': 146517.59, 'Gerdau': 898579.89, 'Haribo': 265333.85}
for k,v in d.items():
d[k] = v+sample[1]
Use a dictionary instead of a list.
#Make the master data structure a Dictionary
myDict = {'Acer':float(481242.74) }
print myDict
#iterate over the newList and update the master dictionary
newList = [['Acer', float(502682.4292)]]
for Company, NewValue in newList:
myDict[Company]=(myDict[Company]+NewValue)
print myDict
Related
I'm trying to look up values in a dictionary by shortened keys (The keys in the dictionary are full length), where the shortened keys are in a different list.
For example, the list might be
names = ["Bob", "Albert", "Man", "Richard"],
and the dictionary I want to look up is as such:
location_dict {"Bob Franklin":"NYC", "Albert":"Chicago", "Manfred":"San Fransisco", "Richard Walker":"Houston"}
The code I have is:
for name in names:
if name.startswith(f'{name}') in location_dict:
print(location_dict[name.startswith('{name}')])
But this doesn't work (because it's self referential, and I need a list of full key names associated with the shortened ones, I understand that much). How do I get the values of a dictionary with shortened key names? I have a list of over a 1000 names like this, and I don't know the most efficient way to do this.
Expected output: If I look up "Bob" from the list of names as a key for the dictionary, then it should return "NYC" from the dictionary
Your condition is wrong. name.startswith(f'{name}') will always return True.
Try this -
for name in names:
for k, v in location_dict.items():
if k.startswith(name):
print(v)
To stop after the first match add a break statement.
for name in names:
for k, v in location_dict.items():
if k.startswith(name):
print(v)
break
Try this in just one line using any():
[v for k,v in location_dict.items() if any(k.startswith(name) for name in names)]
I have a for loop that goes through two lists and combines them in dictionary. Keys are strings (web page headers) and values are lists (containing links).
Sometimes I get the same key from the loop that already exists in the dictionary. Which is fine. But the value is different (new links) and I'd like to update the key's value in a way where I append the links instead of replacing them.
The code looks something like that below. Note: issue_links is a list of URLs
for index, link in enumerate(issue_links):
issue_soup = BeautifulSoup(urllib2.urlopen(link))
image_list = []
for image in issue_soup.findAll('div', 'mags_thumb_article'):
issue_name = issue_soup.findAll('h1','top')[0].text
image_list.append(the_url + image.a['href'])
download_list[issue_name] = image_list
Currently the new links (image_list) that belong to the same issue_name key get overwritten. I'd like instead to append them. Someone told me to use collections.defaultdict module but I'm not familiar with it.
Note: I'm using enumerate because the index gets printed to the console (not included in the code).
Something like this:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
d["b"].append(3)
Then:
print(d)
defaultdict(<class 'list'>, {'b': [3], 'a': [1, 2]})
if download_list.has_key(issume_name):
download_list[issume_name].append(image_list)
else:
download_list[issume_name] = [image_list]
is it right?If you have the same key, append the list.
When I run this code why are resultant two dictionaries not the same. I know it has something to do with how they are declared but as far as I can tell post deceleration but prior to assignment of values they are the same.
H=['DEPTH', 'CALI', 'S-SONIC', 'P-SONIC', 'GR', 'LITH', 'RESISTIVITY', 'NPHI', 'POROS', 'RHOB', 'SWARCH', 'SW_I', 'VP', 'VSH', 'VS']
Val=[]
Val.append(['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'])
Val.append(['16','17','18','19','20','21','22','23','24','25','26','27','28','29','30'])
Dict1={}
for name in H:
Dict1[name] = []
Dict2=dict.fromkeys(H,list())
for line in Val:
values = [float(val) for val in line]
for i, name in enumerate(H):
Dict1[name].append(values[i])
Dict2[name].append(values[i])
print 'DEPTH:', Dict1['DEPTH']
print 'DEPTH:', Dict2['DEPTH']
Thank you for any insight,
Dan
Your problem lies in dict.fromkeys(H, list()). Only one list is being created, and it is being assigned to every key in the dictionary. Add a value to one key, and it gets added for all keys since they are all sharing one list.
You could use a dictionary comprehension instead to create Dict2:
Dict2 = {key: [] for key in H}
I am currently working with a dataframe consisting of a column of 13 letter strings ('13mer') paired with ID codes ('Accession') as such:
However, I would like to create a dictionary in which the Accession codes are the keys with values being the 13mers associated with the accession so that it looks as follows:
{'JO2176': ['IGY....', 'QLG...', 'ESS...', ...],
'CYO21709': ['IGY...', 'TVL...',.............],
...}
Which I've accomplished using this code:
Accession_13mers = {}
for group in grouped:
Accession_13mers[group[0]] = []
for item in group[1].iteritems():
Accession_13mers[group[0]].append(item[1])
However, now I would like to go back through and iterate through the keys for each Accession code and run a function I've defined as find_match_position(reference_sequence, 13mer) which finds the 13mer in in a reference sequence and returns its position. I would then like to append the position as a value for the 13mer which will be the key.
If anyone has any ideas for how I can expedite this process that would be extremely helpful.
Thanks,
Justin
I would suggest creating a new dictionary, whose values are another dictionary. Essentially a nested dictionary.
position_nmers = {}
for key in H1_Access_13mers:
position_nmers[key] = {} # replicate key, val in new dictionary, as a dictionary
for value in H1_Access_13mers[key]:
position_nmers[key][value] = # do something
To introspect the dictionary and make sure it's okay:
print position_nmers
You can iterate over the groupby more cleanly by unpacking:
d = {}
for key, s in df.groupby('Accession')['13mer']:
d[key] = list(s)
This also makes it much clearer where you should put your function!
... However, I think that it might be better suited to an enumerate:
d2 = {}
for pos, val in enumerate(df['13mer']):
d2[val] = pos
Python dictionaries really have me today. I've been pouring over stack, trying to find a way to do a simple append of a new value to an existing key in a python dictionary adn I'm failing at every attempt and using the same syntaxes I see on here.
This is what i am trying to do:
#cursor seach a xls file
definitionQuery_Dict = {}
for row in arcpy.SearchCursor(xls):
# set some source paths from strings in the xls file
dataSourcePath = str(row.getValue("workspace_path")) + "\\" + str(row.getValue("dataSource"))
dataSource = row.getValue("dataSource")
# add items to dictionary. The keys are the dayasource table and the values will be definition (SQL) queries. First test is to see if a defintion query exists in the row and if it does, we want to add the key,value pair to a dictionary.
if row.getValue("Definition_Query") <> None:
# if key already exists, then append a new value to the value list
if row.getValue("dataSource") in definitionQuery_Dict:
definitionQuery_Dict[row.getValue("dataSource")].append(row.getValue("Definition_Query"))
else:
# otherwise, add a new key, value pair
definitionQuery_Dict[row.getValue("dataSource")] = row.getValue("Definition_Query")
I get an attribute error:
AttributeError: 'unicode' object has no attribute 'append'
But I believe I am doing the same as the answer provided here
I've tried various other methods with no luck with various other error messages. i know this is probably simple and maybe I couldn't find the right source on the web, but I'm stuck. Anyone care to help?
Thanks,
Mike
The issue is that you're originally setting the value to be a string (ie the result of row.getValue) but then trying to append it if it already exists. You need to set the original value to a list containing a single string. Change the last line to this:
definitionQuery_Dict[row.getValue("dataSource")] = [row.getValue("Definition_Query")]
(notice the brackets round the value).
ndpu has a good point with the use of defaultdict: but if you're using that, you should always do append - ie replace the whole if/else statement with the append you're currently doing in the if clause.
Your dictionary has keys and values. If you want to add to the values as you go, then each value has to be a type that can be extended/expanded, like a list or another dictionary. Currently each value in your dictionary is a string, where what you want instead is a list containing strings. If you use lists, you can do something like:
mydict = {}
records = [('a', 2), ('b', 3), ('a', 4)]
for key, data in records:
# If this is a new key, create a list to store
# the values
if not key in mydict:
mydict[key] = []
mydict[key].append(data)
Output:
mydict
Out[4]: {'a': [2, 4], 'b': [3]}
Note that even though 'b' only has one value, that single value still has to be put in a list, so that it can be added to later on.
Use collections.defaultdict:
from collections import defaultdict
definitionQuery_Dict = defaultdict(list)
# ...