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?
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.
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.
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.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With