Reputation: 39
I am new to python sorry if I have made any errors
I have a data like this
ENSG1 1:24 2:56 3:47 4:68 5:89
ENSG2 1:25 2:57 3:48 4:69 5:90
ENSG3 1:26 2:58 3:49 4:70 5:91
The first column is the {key} and the remaining columns will be the {values} in the key -> value pair of a dictionary element.
Is this possible in python??
Thanks for the suggestions
Upvotes: 0
Views: 353
Reputation: 39
Based on the above answers and suggestions from many different sites I would like to present my answer to the question I posted
import numpy as np
keys = np.array(("key1","key2","key3"))
values = np.array([['20','30','40'],['56','76','80',],['57','70','89']])
d = {}
for k in set(keys):
d[k] = values[k==keys]
print d
Result:
{'key3': array([['57', '70', '89']],
dtype='|S2')}
{'key3': array([['57', '70', '89']],
dtype='|S2'), 'key2': array([['56', '76', '80']],
dtype='|S2')}
{'key3': array([['57', '70', '89']],
dtype='|S2'), 'key2': array([['56', '76', '80']],
dtype='|S2'), 'key1': array([['20', '30', '40']],
dtype='|S2')}
Thanks for the support rendered by all
Upvotes: 0
Reputation: 824
Your specific example is answered above by @Delirious Lettuce, However the title of the question : Can a dictionary key be a list element, needs further clarifying.
a list is a mutable object, If you change the list indexes it will not reflect in the dictionary keys. Python will create the key upon assignment and will not point at the original index.
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary entry,
Upvotes: 0
Reputation: 3382
>>> test = """\
... ENSG1 1:24 2:56 3:47 4:68 5:89
... ENSG2 1:25 2:57 3:48 4:69 5:90
... ENSG3 1:26 2:58 3:49 4:70 5:91"""
>>> result = {}
>>> for row in test.splitlines():
... key, *values = row.split()
... result[key] = values
...
>>> result
{'ENSG1': ['1:24', '2:56', '3:47', '4:68', '5:89'], 'ENSG2': ['1:25', '2:57', '3:48', '4:69', '5:90'], 'ENSG3': ['1:26', '2:58', '3:49', '4:70', '5:91']}
Upvotes: 1