0

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}

  • `{k: v for k, v in zip(tuple1, tuple2)}` or `dict(zip(tuple1, tuple2))`? – deadshot Jul 11 '22 at 09:40
  • 1
    Does this answer your question? [How can I take two tuples to produce a dictionary?](https://stackoverflow.com/questions/44706935/how-can-i-take-two-tuples-to-produce-a-dictionary) – deadshot Jul 11 '22 at 09:42

2 Answers2

3

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)}
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

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}