Home > Back-end >  Tuples to dictionary , where first tuple are keys and second tuple is corresponding elements?
Tuples to dictionary , where first tuple are keys and second tuple is corresponding elements?

Time:07-11

need a function that takes in two tuples and returns a dictionary in which the elements of the first tuple are used as keys, and the corresponding elements of the second

for example, calling tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4)) will return {'a':1, 'b':2, 'c':3}

CodePudding user response:

you could use dict with zip method:

  • zip() to merge two or more iterables into tuples of two.
  • dict() function creates a dictionary.
def tuples_to_dict(x,y):
    return dict(zip(x,y))

result {'a': 4, 'b': 2, 'c': 3}

Other way using enumerate and dictionary comprehension:

def tuples_to_dict(x,y):
    return {x[i]:y[i] for i,_ in enumerate(x)}

CodePudding user response:

If you needed it to not insert the second 'a' you can check prior to inserting the value and not do so if already present:


def tuples_to_dict(first, second):
    out = {}
    for k, v in zip(first, second):
        if k not in out:
            out[k] = v
    return out

tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4))
{'a': 1, 'b': 2, 'c': 3}
  • Related