directyou
directyou

Reputation: 1

Tuples to dictionary , where first tuple are keys and second tuple is corresponding elements?

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}

Upvotes: 0

Views: 56

Answers (2)

Derryn Knife
Derryn Knife

Reputation: 104

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))

Output:

{'a': 1, 'b': 2, 'c': 3}

Upvotes: 1

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9263

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)}

Upvotes: 3

Related Questions