Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of List to Key-Value Pairs

I have a string which is semicolon delimited and then space delimited:

'gene_id EFNB2; Gene_type cDNA_supported; transcript_id EFNB2.aAug10; product_id EFNB2.aAug10;'

I want to create a dictionary in one line by splitting based on the delimiters but so far I can only get to a list of lists:

filter(None,[x.split() for x in atts.split(';')])

Which gives me:

[['gene_id', 'EFNB2'], ['Gene_type', 'cDNA_supported'], ['transcript_id', 'EFNB2.aAug10'], ['product_id', 'EFNB2.aAug10']]

When what I want is:

{'gene_id': 'EFNB2', 'Gene_type': 'cDNA_supported', 'transcript_id': 'EFNB2.aAug10', 'product_id': 'EFNB2.aAug10'}

I have tried:

filter(None,{k:v for k,v in x.split() for x in atts.split(';')})

but it gives me nothing. Anybody know how to accomplish this?

like image 393
Dave Avatar asked May 18 '16 16:05

Dave


People also ask

How do I get a list of values from a list of keys?

To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys] that iterates over each key in the list of keys and puts the associated value d[key] into the newly-created list.

Can list have key-value pairs?

A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair. A key in the key-value pair must be immutable.

Can Python list have key-value pairs?

There is no "key-value pair" as a general thing in Python. Why are you using a list instead of a dictionary? A dictionary contains key-value pairs, but there's no builtin notion of a key-value pair that's not in a dictionary.


1 Answers

You are very close now, you can just call dict on your list of lists:

>>> lst = [['gene_id', 'EFNB2'], ['Gene_type', 'cDNA_supported'], ['transcript_id', 'EFNB2.aAug10'], ['product_id', 'EFNB2.aAug10']]
>>> dict(lst)
{'Gene_type': 'cDNA_supported',
 'gene_id': 'EFNB2',
 'product_id': 'EFNB2.aAug10',
 'transcript_id': 'EFNB2.aAug10'}
like image 199
wim Avatar answered Sep 19 '22 10:09

wim