Galaxy
Galaxy

Reputation: 2012

Python3 print selected values of dict

In this simple code to read a tsv file of many columes:

InColnames = ['Chr','Pos','Ref','Alt']
tsvin = csv.DictReader(fin, delimiter='\t')
for row in tsvin:
    print(', '.join(row[InColnames]))

How can I make the print work ?

Upvotes: 0

Views: 37

Answers (1)

user2390182
user2390182

Reputation: 73490

The following will do:

for row in tsvin:
    print(', '.join(row[col] for col in InCOlNames))

You cannot pass a list of keys to the dict's item-lookup and magically get a list of values. You have to somehow iterate the keys and retrieve each one's value individually. The approach at hand uses a generator expression for that.

Upvotes: 1

Related Questions