0

i have a tuple of suspects those suspects exist in dictionary and in the dictionary i have a tuple value

i try to unpacking the values to varibles

suspects = (
 {'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
 {'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
 {'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
 )
for t in suspects:
   for name, weapon,location in t.items():

there i got stacked. i try to run python tutor to see a feeback of my faults, but i can't understand how can i extract the specific value with unpacking solution

for examp solution: Name = Anne , Weapon = Derringer , Location = Caesarea

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Johny8462
  • 11
  • 4

3 Answers3

0

Try this on for size:

suspects = (
 {'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
 {'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
 {'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
 )
for t in suspects:
    name = t['name']
    weapon, location = t['evidences']
    print(name, weapon, location)

Output:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule

EDIT: If you must unpack twice, here's an uglier way to do it that does unpack twice (key, value) and (weapon, location) :

suspects = (
 {'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
 {'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
 {'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
 )
for t in suspects:
    name = None
    weapon = None
    location = None
    for key, value in t.items():
       if key == "name":
          name = value
       elif key == "evidences":
           weapon, location = value
    print(name, weapon, location)
Chance
  • 440
  • 2
  • 6
0

This would be the way to do it:

for t in suspects:
    weapon, location = t["evidences"]
    print(f"Name: {t['name']} Weapon: {weapon} Location: {location}")
carloslockward
  • 335
  • 3
  • 8
0

Your data structure isn't conducive to what you're trying to do exactly. If there's a specific reason why you want to keep this particular structure, then use the answers provided. If, however, you're open to using a different data structure:

suspects = {"Anne": ("derringer", "Caesarea"),
            "Taotao": ("derringer", "Petersen House"),
            "Pilpelet": ("Master Sword", "Hyrule")}

for name, (weapon, location) in suspects.items():
    print(name, weapon, location)

Output:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule
ddejohn
  • 8,775
  • 3
  • 17
  • 30
  • its a part from mission that i have to solve this with unpcaking method in this data structure i know that if i change the data structure its woukd be very comfort to solve ... thank for your answer – Johny8462 Feb 17 '21 at 21:20