Home > Software engineering >  Accessing first element of a tuple in a list of tuples, in a list - python
Accessing first element of a tuple in a list of tuples, in a list - python

Time:05-27

Im fairly new to python, and I have a list of two lists, with 5 tuples each, called 'cos':

cos =  ([('B6409', 0.9997), ('S4193', 0.9996), ('C9826', 0.9995), ('J6706', 0.9994), ('Q0781', 0.9993)] , [('A5474', 0.9985), ('H1286', 0.9981), ('Y1178', 0.998), ('D2742', 0.9979), ('A7668', 0.9979)])

Id like to iterate over this list and match the first element of each tuple, ie: 'B6409' and 'S4193' with the keys of a dictionary called 'dist', ie: 'R7033' , 'B6409' etc...

dist = { 'R7033': [93.9636, 32.6327, 33.092]  ,   'V3259': [84.8378, 27.3658, 29.1537]  ,  'B6409': [55.6789, 67.5673, 89.7856] }

So effectively an if statement saying 'if the first element of each tuple in each list(two of them) is equal to a key in the dictionary 'dict', perform a calculation to sum up the values of that key. So for example since the first element of one of the tuples in the list 'cos' is 'B6409', and it IS one of they keys in dictionary 'dict', sum up the list of values of key 'B6409'.

Im just getting confused on the indexing of elements within the list of list with tuples and so far i have done only know to use

for i in dist.keys():
 for j in cos....
     if i == cos[?][?][?]:
         sum1 = sum(dist[i])

how is a way i can do this iteration loop? thanks

CodePudding user response:

If I understood your intention correctly, then you could use a comprehension to generate a list of keys from cos and then another comprehension to generate a dictionary whose values are the corresponding sums:

cos =  ([('B6409', 0.9997), ('S4193', 0.9996), ('C9826', 0.9995), ('J6706', 0.9994), ('Q0781', 0.9993)] , [('A5474', 0.9985), ('H1286', 0.9981), ('Y1178', 0.998), ('D2742', 0.9979), ('A7668', 0.9979)])
dist = { 'R7033': [93.9636, 32.6327, 33.092]  ,   'V3259': [84.8378, 27.3658, 29.1537]  ,  'B6409': [55.6789, 67.5673, 89.7856] }

keys = [item[0][0] for item in cos]
key_to_sum_dict = {key: sum(dist[key]) for key in keys if key in dist}

Which gives {'B6409': 213.0318}.

CodePudding user response:

A way to iterate over cos would be:

for dist_key in dist.keys():
  for cos_list in cos:
    for cos_tuple in cos_list:
      if dist_key == cos_tuple[0]:
        sum1 = sum(dist[dist_key])
  • Related