Hannah Hannah - 1 year ago 81
Python Question

Python: Accessing individual values in a dictionary of a list of tuples

I have a dictionary in Python where each key has a set of ten tuples. I am trying to iterate through the dictionary access the individual elements within each tuple- how should I go about that?

The dictionary looks like this:

{'Key1': [(Hi, 1), (Bye, 2)], 'Key2': [(Cats, Blue), (Dogs, Red)]}

Say I want vectors of the Keys, a vectors of the first elements [Hi, Bye, Cats, Dogs] and one of the second [1,2, Blue, red]

This is the code I was attempting:

for key in dict:
for tuplelist in dict:

I know this is incorrect but I am not sure how to go about fixing it.

Answer Source

I assume you mean your dict is:

your_dict = {'Key1': [('Hi', 1), ('Bye', 2)], 'Key2': [('Cats', 'Blue'), ('Dogs', 'Red')]}

You can iterate over all the keys, get whatever tuple is in there, and then iterate over all the entries inside that tuple. There probably is an easier way but this should at least get you there:

for key in your_dict:
    for t in your_dict[key]:
        for i in t:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download