Adding Multiple Values to Single Key in Python Dictionary Comprehension - python

I am using a dictionary comprension to be created from an excel spreadsheet. The first column of the excel sheet are the keys and the next 3 columns are the values. I'd like to build a dictionary comprehension that I can use later in my script. I understand a dictionary comprehension to be built as:
d = {key: value for (key, value) in sequence}
and I can do this and get a nice key,value dictionary:
d = {str(row.getValue("Column1")): str(row.getValue("Column2")) for i in arcpy.SearchCursor(xls,"[Column1] = 'Lake_Huron'")}
I'm just not sure how I would go about adding the other 2 columns in the dictionary comprehension as 2nd and 3rd values to the key? Is this possible?

d = {str(row.getValue("Column1")): (str(row.getValue("Column2")), str(row.getValue("Column3")), str(row.getValue("Column4"))) for i in arcpy.SearchCursor(xls,"[Column1] = 'Lake_Huron'")}
OR
d = {str(row.getValue("Column1")): (str(row.getValue("Column{0}".format(i)) for i in [2, 3, 4]) for i in arcpy.SearchCursor(xls,"[Column1] = 'Lake_Huron'")}

Related

match the column value based on previous paired values in python

i have one dictionary with pair of keys and values and list
dict={0.000806:1.341382,0.023886:39.63012,7.525935:63.89669,7.571048:62.47208}
list=[7.525935,7.571048,0.000806,0.023886]
with this following list and dictionaries my expected output is
expected output:
{7.525937:63.89669,
7.571048:62.47208,
0.000806:1.341382,
0.023886:0.023886}
thing_category=dict((t,c) for c,t in category_thing.items())
list=[7.525935,7.571048,0.000806,0.023886]
for stuff in list_of_things:
if stuff in category_thing:
print(stuff)
with the help of list values match the dictionary values how can i do that i tried merge and map also but it didn't worked
with help of this 2 columns i have to match the values with anotherexpecting matched values with help of values in first figure
You can use a comprehension to construct a new dict with keys in the order of the list_ entries:
dict_ = {0.000806:1.341382,0.023886:39.63012,7.525935:63.89669,7.571048:62.47208}
list_ = [7.525935,7.571048,0.000806,0.023886]
{k: dict_[k] for k in list_}
However, you might run into problems with float keys if there are slight numeric differences.

Store list of dictionaries as a DataFrame

Suppose I have List of dictionaries as
l = [{'car':'good'},
{'mileage':'high'},
{'interior':'stylish'},
{'car':'bad'},
{'engine':'powerful'},
{'safety':'low'}]
Basically these are noun-adjective pairs.
How can I visualize whats the most associated list of adjective to
lets say car here.
How to convert this to Data frame? , I have tried pd.Dataframe(l)
, but here the key is not the column name so gets little bit tricky
here.
Any help would be appreciated.
Given that you want this to be done column-wise, then you have to re-structure your list of dictionaries. You need to have one dictionary to represent one row. Therefore, your example list should be (I added a second row for better explainability):
l = [
{'car':'good','mileage':'high','interior':'stylish','car':'bad','engine':'powerful','safety':'low'}, # row 1
{'car':'bad','mileage':'low','interior':'old','car':'bad','engine':'powerful','safety':'low'} # row 2
]
At this point, all you have to do is call pd.DataFrame(l).
EDIT: Based on your comments, I think you need to convert the dictionary to a list to get your desired result. Here is a quick way (I'm sure it can be much more efficient):
l = [{'car':'good'},
{'mileage':'high'},
{'interior':'stylish'},
{'car':'bad'},
{'engine':'powerful'},
{'safety':'low'}]
new_list = []
for item in l:
for key, value in item.items():
temp = [key,value]
new_list.append(temp)
df = pd.DataFrame(new_list, columns=['Noun', 'Adjective'])
You can construct your DataFrame by giving a list of tuples. To get tuples from a dict use the method items(). Construct the list of tuples with a list comprehension by taking the first tuple of each items.
import pandas as pd
df=pd.DataFrame(data=[d.items()[0] for d in l],columns=['A','B'])
print df
Gives :
A B
0 car good
1 mileage high
2 interior stylish
3 car bad
4 engine powerful
5 safety low

Can't work out how to apply multi-keyed dictionary vals back to dataframe column

I have a dictionary with 2 keys for every 1 value like so:
Initial Dict
Key : ('106338', '2006-12-27') , Value : []
Dict after populating
Key : ('106338', '2006-12-27') , Value : [8, 7, 9, 8, 7]
The value for each key pair is an array holding some amount of information which I need the length of. I created this dictionary by first itertupling across a dataframe and generating key pairs and empty arrays for each unique record. I then iterated across it again and populated the arrays with the information I need by appending values to the end of each key pair. Key pairs were generated from row values. The first item in the key is the Identification number for the asset and the second item is the date for the asset. Here is code for dict creation:
perm_dict = {}
for row in df_perm.itertuples():
perm_dict[str(row[1]),str(row[3])] = []
for row in df_perm.itertuples():
if row[6].to_datetime().date() < row[9].to_datetime().date() and row[9].to_datetime().date() < row[5].to_datetime().date():
perm_dict[str(row[1]), str(row[3])].append(row[10])
My problem is that I now need to call those values back via the key pairs by iterating through the original dataframe so I can take my array lengths and make a new column out of them. Screenshot of DataFrame:
I am having trouble working out a solution in my head for applying these counts back to the original dataframe as a new column for only the rows with key matches. I can't iterate back through to add them because then I'd be modifying my original DF and I've read that's a big no-no. Any help that you all may be able to provide would be greatly appreciated! Also please lmk if I need to include more information as I can provide more.
Edit1
Here are the outputs after running the dictionary comprehension code provided.
This might be what you are looking for.
import pandas as pd
# sample data
d = {('106338', '2006-12-27'): [8, 7, 9, 8, 7]}
df = pd.DataFrame([['106338', '2006-12-27']], columns=['Key1', 'Key2'])
# first make dictionary mapping to length of list
d_len = {k: len(v) for k, v in d.items()}
# perform mapping
df['Len'] = list(map(d_len.get, (zip(*(df[col] for col in ('Key1', 'Key2'))))))
# output
# Key1 Key2 Len
# 106338 2006-12-27 5

Make Dictionary from 2D Array Python?

I have a 2D array as follows.
[['FE0456143', '218.04'], ['FB1357448', '217.52'], ['FB1482960', '222.70'], ['FB1483107', '223.32'], ['FE0456556', '12429.67'], ['FE0456594', '213.71'], ['FB1483056', '218.86'], ['FE0456061', '12392.33'], ['FB1482479', '223.35']]
The first element is the key while the second is the value. I have tried:
keys = zip(*data)[0]
vals = zip(*data)[1]
dic(zip(keys,vals))
However some elements of the array may have duplicate keys, and the elements are not corresponding to them? I want all of the keys to have 3 values associated with it?
Sounds like you want a 1 to many mapping. You can have this if you make your value a list:
from collections import defaultdict
d = defaultdict(list)
for k, v in data:
d[k].append(v)

Sorting a dictionary which is exported to excel?

Ok, So I have a dictionary with values which are contained as lists, which is what I've been looking for... I was wondering if there was a way to sort this which will also display the values of the lists in separate columns... I have used this code to split the values into different columns:
writer = csv.writer(csvfile, delimiter=',')
for key, value in finaldict.iteritems():
writer.writerow([key] + value)
Is there any way to make this sort the keys before writing it? Anything I seem to try either doesn't sort it, generates an error, or breaks the part where it changes the list into separate columns... So if you don't understand what I am saying for example lets say I have a dictionary
finaldict = {'A': [2 , 1], 'C' [3, 3], 'B' [4, 3]}
I'm looking for this in the excel file:
Parameter Val1 Val2
A 2 1
B 4 3
C 3 3
But currently I get this:
Parameter Val1 Val2
A 2 1
C 3 3
B 4 3
I'm grateful for the replies guys thank you!
An alternative to the other answer (a bit cleaner, imho):
for key in sorted(finaldict.keys()):
writer.writerow([key] + finaldict[key])
Use sorted to return a list of tuples containing the key and value, then write that instead:
for key, value in sorted(finaldict.iteritems(), key=lambda: L[0]):
writer.writerow([key] + value)

Categories