简体   繁体   中英

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}

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

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM