My question is how to turn two tuples in a dictionary, and have it so that if there are two strings that are the same in the first tuple, it returns the first element from the second tuple:
e.g.
def tuples_to_dict(x,y):
mydict= {}
for k,v in zip(x,y):
mydict[k]=v
return mydict
tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4))
however this outputs:
{'a': 4, 'b': 2, 'c': 3}
However I would like it to be:
{'a': 1, 'b': 2, 'c': 3}
Apologies if this is too simple a question to be stuck on! I know I have to add more to my code which is why its returning the wrong output I want, I've had a look at other resources however it doesnt answer my specific question. I've thought about putting an if
statement and do x.count(k)>=1:
However I didnt know where to go from there.
CodePudding user response:
Just one extra check needed to see whether the key is already in the dictionary.
def tuples_to_dict(x,y):
mydict= {}
for k,v in zip(x,y):
if k not in mydict:
mydict[k]=v
return mydict
CodePudding user response:
Inserting the element in reversed order would achieve what you need:
def tuples_to_dict(x, y):
return dict(reversed(list(zip(x, y))))
tuples_to_dict(('a', 'b', 'c', 'a'), (1, 2, 3, 4))
OUTPUT
{'a': 1, 'c': 3, 'b': 2}
Ideally you should check that the two lists have the same length, to avoid unexpected results: zip
will truncate to the shortest list by default.
There could be a debate if reversing before or after zipping, but I think the latter is better for the following reason - if you pass list of different lengths:
x = ('a', 'b', 'c', 'a')
y = (1, 2, 3)
dict(reversed(list(zip(x, y))))
dict(zip(reversed(x), reversed(y)))
OUTPUT
{'c': 3, 'b': 2, 'a': 1} # This is more in line with what I would expect
{'a': 3, 'c': 2, 'b': 1}
In Python 3.10 you can force zip
to throw an exception in case the zipped lists have different lengths (passing strict=True
), and that would avoid any issue in this respect.