open csv file in python to customize dictionary [duplicate]

2024/7/7 6:46:11

I would like to know to load this csv file:

Epitope,ID,Frequency,AssayAVNIVGYSNAQGVDY,123431,27.0,TetramerDIKYTWNVPKI,887473,50.0,3HLRQMRTVTPIRMQGG,34234,11.9,Elispot

into a python dictionary like this:

d = {'AVNIVGYSNAQGVDY': [ID[123431],Frequency[27.0],Assay['Tetramer']], 'DIKYTWNVPKI': [ID[887473],Frequency[50.0],Assay['3H']], 'LRQMRTVTPIRMQGG': [ID[34234],Frequency[11.9],Assay['Elispot']]}

I am working with lists since my actual file is bigger and I will append more values to those lists.

Answer

First, do you know about the csv module? If not, read the introduction and examples to the point where you know how to get an iterable of rows. Print each one out, and they'll look something like this:

['AVNIVGYSNAQGVDY', '123431', '27.0', 'Tetramer']

Or, if you use a DictReader:

{'Epitope': 'AVNIVGYSNAQGVDY', 'ID': '123431', 'Frequency': '27.0', 'Assay': 'Tetramer'}

But you don't want a list of lists, or a list of dictionaries; you want a dictionary of lists, where each key is the Epitope from a row, and the corresponding value is the other three values, right? So… just insert each row into a dictionary that way:

d = {}
with open(path, 'rb') as f:with csv.DictReader(f) as reader:for row in reader:d[row['Epitope']] = [row['ID'], row['Frequency'], row['Assay']]

(This would be more compact with a plain reader instead of a DictReader, but I think it's more readable this way if you come back to the code a few months from now.)

You also want to convert the values and use them as keys for another lookup, but that should be trivial. For example:

            row_id = ID[int(row['ID'])]row_frequency = Frequency[float(row['Frequency'])]row_assay = Assay[row['Assay']]d[row['Epitope']] = [row_id, row_frequency, row_assay]

You can clean this up a bit by writing the row transformation as a function, and then just using a dictionary comprehension:

with open(path, 'rb') as f:with csv.DictReader(f) as reader:d = {row['Epitope']: process_row(row) for row in reader}
https://en.xdnf.cn/q/120169.html

Related Q&A

How does UserPassesTestMixin in django work?

views.pyclass ProfileEdit(UserPassesTestMixin, UpdateView):model = Userform_class = ProfileFormtemplate_name="profile/profile_new.html"def test_func(self):x = self.request.user.idprint (x)y =…

How to extract URL from HTML anchor element using Python3? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Why does using open(filename) fail with filename is not defined?

I want to open a text file containing a column of words and create a list or, alternatively, a string containing these words. Why do I get this error: >>> with open(some_file.txt, r) as some_f…

Read Excel file which has one of the column as Hyperlink through python

I have to read an Excel file Using python. By the time I use xl = pd.ExcelFile("abc.xlsx")The column values which had hyperlink assigned to it becomes a simple number without any hyperlink.Is…

How can I create n number of files in python?

say user gives a number n=3 then I have to create 3 files dynamically. How will I do that? What can be the names of those files. Specifically I want n number of .jpg file created.

For loop doesnt append info correctly into 2D array

I have created an empty 2D array. When I try to add stuff inside of it, it doesnt do so properly. Each index contains the appropriate info, but for some reason, carries the info from the previous into …

How to merge two strings in python?

I need to merge strings together to create one string. For example the strings for "hello" that need to be combined are: [H----], [-E---], [--LL-], and [----O]This is the current code I have …

ValueError: too many values to unpack (expected 3)?

I have been having issues with the code I am trying to right with the model I am trying to code the following error has appeared and being a relative novice I am unsure of how to resolve it.ValueError …

Finding a hello word in a different string, which it has hello in it

I should find a hello word in a string, which I gave it from input. Here is the code that I currently have, but I cannot match hello with the character list.mylist = it can be any letter plus hello in …

Building Permutation with Python

Im trying to write a programme to get all permutations of a string of letter using recursion. As Im a beginner in Python, I learnt about recursion with examples like Fibonacci Number and Factorial. I u…