I am writing a python script using excel and I am fairly new to programming
Representation of data
I want the use the values in column C, D and E to get the the value in column B.
I tried using a dictionary but it seems you can only use one key with a dictionary.
What data structure can I use for this situation?
You can use a tuple for your dictionary's key. So it would look something like this:
myDict = {}
myDict[(C, D, E)] = A
Related
Classic, but i'm new to python... and have a problem a can't manage to solve. I'm assuming it's fairly easy.
I have two csv files, one scraped from the web(a=[]), containing 20000+ lines, the other exported from a local system [b=[]] 80+ lines.
I have open the files and stored the data in list a and b. Theey are structured like the example below.
a = [[1,'a','b','a#b',11],
[2,'c','d','c#b',22],
[3,'e','f','e#b',33]]
b = [['a','banana','A',100],
['e','apple','A',100]]
Now i would like to go through list a and when index 1 of every sublist in list a is equal to index 0 of the sublist in list b it shall append index 3 and 4 of a. So I would end up with
c= [['a','banana','A',100,'a#b',11],
['e','apple','A',100,'e#b',33],]
How to achive this. The solution don't need to be fast if it teaches something about the structure in Python. But if solved easy with pandas i'm all ears.
If this fora is not for questions like this i'm sorry for the time.
This is not optimized and isn't efficient time complexity vice, but it's readable and does the job.
c = []
for a_entry in a:
for b_entry in b:
if a_entry[1] == b_entry[0]:
c.append(b_entry + a_entry[3:])
make a dictionary ({index1:[index2,index3],...}) by iterating over a
for each item/sublist use index 1 for the key and indices 2 and 3 for the value
do the same thing for b except use index zero for the key and [1:] for the value
iterate over the items in the b dictionary
use the key of each item to get a value from the a dictionary
if there is one, extend the b item's value
reconstruct b from the modified dictionary
I was using pyomo and I have to create some dictionaries with multiple keys to work with it.
So, for example, I have these three lists below, and I want to associate Demand with both Product and Client.
They're already ordered and contain the same amount of entries.
Product = ["A","B","C","A","B","C"]
Client = ["Client1","Client1","Client1","Client2","Client2","Client2"]
Demand = [1,2,3,4,5,6]
And so I wanted the following output:
Demand_dict = {("A","Client1"):1, ("B","Client1"):2,("C","Client1"):3,("A","Client2"):4, ("B","Client2"):5,("C","Client2"):6,
I tried usind dict(zip) but I can't put multiple keys on th first argument.
Any easy way of doing it?
Thanks
This should give you the result you need using a dictionary comprehension:
Demand_dict = {(p, c): d for p, c, d in zip(Product, Client, Demand)}
It zips the three lists and then iterates over the 3-tuples using the first two values as the key for a dictionary entry and the third value as the value.
I'm trying to write something that answers "what are the possible values in every column?"
I created a dictionary called all_col_vals and iterate from 1 to however many columns my dataframe has. However, when reading about this online, someone stated this looked too much like Java and the more pythonic way would be to use zip. I can't see how I could use zip here.
all_col_vals = {}
for index in range(RCSRdf.shape[1]):
all_col_vals[RCSRdf.iloc[:,index].name] = set(RCSRdf.iloc[:,index])
The output looks like 'CFN Network': {nan, 'N521', 'N536', 'N401', 'N612', 'N204'}, 'Exam': {'EXRC', 'MXRN', 'HXRT', 'MXRC'} and shows all the possible values for that specific column. The key is the column name.
I think #piRSquared's comment is the best option, so I'm going to steal it as an answer and add some explanation.
Answer
Assuming you don't have duplicate columns, use the following:
{k : {*df[k]} for k in df}
Explanation
k represents a column name in df. You don't have to use the .columns attribute to access them because a pandas.DataFrame works similarly to a python dict
df[k] represents the series k
{*df[k]} unpacks the values from the series and places them in a set ({}) which only keeps distinct elements by definition (see definition of a set).
Lastly, using list comprehension to create the dict is faster than defining an empty dict and adding new keys to it via a for-loop.
I have a Python dictionary which looks like this:
alphabetic_dict = {
'a':['apple', 'ant', 'atlas'],
'b':['bee', 'beer','bat'],
'c':['car', 'cash', 'computer']
}
What I want to do is, given one of the values within a list, print the corresponding key. For example, if I write car, I want my program to output something like That value corresponds to 'c'. It might seem a silly thing, but I've never worked with a dictionary containing lists as values, so I'm very confused.
Search the value (which is a list) for the thing you;re looking for
for k, v in alphabetic_dict.items()
if 'car' in v:
print k
input = 'c'
for key, values in alphabetic_dict.items():
if input in values:
print(f'That value corresponds to {key}')
This uses f-strings which were introduced in python 3.6
I am currently attempting to modify a series of programs by utilizing dictionaries as opposed to arrays. I have columns of raw information in a file, which is then read into an ASCII csv file. I need to convert this file into a dictionary, so that it can be fed into another program.
I used a numpy.genfromtxt to pull out the information i need from the csv file, following this format:
a,b,c,d = np.genfromtxt("file",delimiter = ',', unpack = true)
this step works completely fine.
I then attempt to build a dictionary:
ouputDict = dict([a,a],[b,b],[c,c],[d,d])
As i understand it, this should make the key "a" in the dictionary a correspond to the array "a".
thus if:
a = [1,2,3,4]
then:
outputDict[a][0] = 1
However, when i attempt to create this dictionary i receive the following error:
TypeError: unhashable type: 'numpy.ndarray'
Why can't I construct an array in this fashion and what is the workaround, if any? Any help will be greatly appreciated!
You can do this even with using collections
Declare your dictionary as:
Dictionary = {}; // {} makes it a key, value pair dictionary
add your value for which you want an array as a key by declaring
Dictionary[a] = [1,2,3,4]; // [] makes it an array
So now your dictionary will look like
{a: [1,2,3,4]}
Which means for key a, you have an array and you can insert data in that which you can access like dictionary[a][0] which will give the value 1 and so on. :)
Btw.. If you look into examples of a dictionary, array and key value pairs, nested dictionary, your concept will get clearer.
Copied from my comment:
Correct dictionary formats:
{'a':a, 'b':b,...}, or
dict(a=a, b=b,...)
dict([('a', a), ('b', b),...])
The goal is to make the strings 'a','b',etc the keys, not the variable values.