Here is a list of 6 tuples:
listoftuples = [
( { 'd1':[ {'start': 1.2, 'end': 2.7}, {'start': 3.0, 'end': 4.0} ] }, [] ),
( { 'd2':[ {'start': 1.4, 'end': 2.3}, {'start': 3.2, 'end': 4.3} ] }, [] ),
( { 'd3':[ {'start': 1.7, 'end': 2.0}, {'start': 3.5, 'end': 4.0} ] }, [] ),
( { 'd4':[ {'start': 1.5, 'end': 2.4}, {'start': 3.7, 'end': 4.2} ] }, [] ),
( { 'd5':[ {'start': 1.3, 'end': 2.0}, {'start': 3.0, 'end': 4.0} ] }, [] ),
( { 'd6':[ {'start': 1.1, 'end': 2.6}, {'start': 3.6, 'end': 4.0} ] }, [] ),
]
Each tuple contains a dictionary and an empty list. And each dictionary contains a list of 2 dictionaries.
I can´t find the way to loop over all dictionaries and get all the values for the key "start". This would be the result I am looking for:
result_list = [1.2,3.0,1.4,3.2,1.5,3.5,1.3,3.7,1.3,3.0,1.1,3.6]
Any help would be greatly appreciated. Thanks in advance.
CodePudding user response:
You can do this with list comprehension,
In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]
Out[1]: [1.2, 3.0, 1.4, 3.2, 1.7, 3.5, 1.5, 3.7, 1.3, 3.0, 1.1, 3.6]
CodePudding user response:
the mentioned task can also be done by using regex.
import re
listoftuples [...]
res = []
for item in listoftuples:
res = list(map(float, re.findall(r'(\d \.\d )', f'{item}')))
print(res)
result: [1.2, 2.7, 3.0, 4.0, 1.4, 2.3, 3.2, 4.3, 1.7, 2.0, 3.5, 4.0, 1.5, 2.4, 3.7, 4.2, 1.3, 2.0, 3.0, 4.0, 1.1, 2.6, 3.6, 4.0]