I am trying to Taking identical 1st element of a list and assigning it as 1st element of the list. I was told it can be done by using defaultdict from collections module but is there a way i can do this without using the Collections library.
What i have:
mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]]
What i am looking to do:
mapping = [['Tom',[ 'BTPS 1.500 625', 0.702604], [ 'BTPS 2.000 1225', 0.724939]],['Max',[ 'OBL 0.0 421', 0.766102],['DBR 3.250 721', 0.887863]]]
You should use a dict / defaultdict to group the data by name, using the first element which is the key as the name, slicing the rest of the data and appending that as a value:
from collections import defaultdict
d = defaultdict(list)
for sub in mapping:
d[sub[0]].append(sub[1:])
print(d)
Which would give you:
defaultdict(<type 'list'>, {'Max': [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]], 'Tom': [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]})
Or if the order matters, use an OrderedDict :
from collections import OrderedDict
d = OrderedDict()
for sub in mapping:
d.setdefault(sub[0],[]).append(sub[1:])
That gives you:
OrderedDict([('Tom', [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]), ('Max', [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]])])
Without any imports, just use a regular dict again using dict.setdefault :
d = {}
for sub in mapping:
d.setdefault(sub[0],[]).append(sub[1:])
print(d)
Using setdefault, if the key is not in the dict it gets added with a list as the value, if it does exist it just appends the value.
You can loop over the names in mapping and add to dictionary.
mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]]
#using dictionary to store output
mapping_dict=dict()
for items in mapping:
if items[0] in mapping_dict:
mapping_dict[items[0]].append([items[1],items[2]])
else:
mapping_dict[items[0]]=[items[1],items[2]]
print mapping_dict
Output: {'Max': ['OBL 0.0 421', 0.766102, ['DBR 3.250 721', 0.887863]], 'Tom': ['BTPS 1.500 625', 0.702604, ['BTPS 2.000 1225', 0.724939]]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.