+ 2

Can you combine two tuples into one dictionary? Update: Answered.

Hi all, I was trying some code in the playground, trying to combine two tuples (I used tuples because I don't think strings would be possible since I thought I'd learned dictionaries can only take immutable data types) into a dictionary, but I can't get it right. Does anyone know how I could get this? Team = ["Jan", "Piet", "Hans", "Henk", "Anne", "Fleur", "Hannah"] Players = ["Player: " + x for x in Team] print(Players) Vast_team = tuple(Players) print(Vast_team) Scores = (81, 36, 72, 24, 55, 56, 12) Wrong_attempt = {Vast_team:Scores} print(Wrong_attempt) This outputs {('Player: Jan', 'Player: Piet', 'Player: Hans', 'Player: Henk', 'Player: Anne', 'Player: Fleur', 'Player: Hannah'): (81, 36, 72, 24, 55, 56, 12)} How can I make a dictionary where I pair the items from "Vast_team" as keys to the items from "Scores" as values? Player_scores = {"Player: Jan : 81, Player: Piet : 36, etc"}? Thnx in advance!

16th Jun 2024, 9:57 AM
Keetie
5 odpowiedzi
+ 1
You can merge the `Vast_team` and `Scores` as dictionary with `zip()` inbuilt function. `zip` function accepts any iterables such as tuples, lists, and sets. # Note that the `zip` function return `zip` object # we need to convert it into dictionary using `dict()` result = dict(zip(Vast_team, Scores)) print(result) Output: {"Player: Jan": 81, "Player: Piet": 36, ...} You can check out the documentation of `zip` function by write code `help(zip)`.
17th Jun 2024, 3:13 PM
Dhefa デファ
Dhefa デファ - avatar
+ 9
Keetie , 2 possible approaches: (1) use an index generated from a range. so you can access both of the input tuples in parallel and store the pairs in a dictionary. (2) we can use the python zip() builtin function to create the pairs and store them in a dictionary. zip() can take the 2 tuples as arguments. https://docs.python.org/3/library/functions.html#zip
16th Jun 2024, 11:07 AM
Lothar
Lothar - avatar
+ 3
Lothar , You're right, I forgot myself - sorry. I deleted the answer, and maybe that hasn't been seen yet.
16th Jun 2024, 5:35 PM
JaScript
JaScript - avatar
+ 1
Hi Lothar, Thankyou for your anwser. I'm actually quite new to coding and I don't understand neither of the two options you suggested. Could you maybe explain the first option a little more? I have not worked with zip() yet, so I think that one might be a little too hard right now. Thankyou!
17th Jun 2024, 11:30 AM
Keetie
+ 1
Thnx Defa! I used Zip and it worked. I tried to read the explanation given with help(zip), but I don't understand it yet. Maybe I'll understand it later on.
18th Jun 2024, 1:38 PM
Keetie