Christopher Pisz
Christopher Pisz

Reputation: 4010

Dict Comprehension - Why is the debugger telling me my dict is a set?

I am learning python. I tried to make a "dict comprehension." I am confused why python is telling me that 'poops' is a set rather than a dict.

# dictionary<string, tuple<string, string>>
DATA = {
    'A': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'B': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'C': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'D': (
        ('Label1', 'Category1'),
        ('Label4', 'Category2'),
    )
}


class Poop:
    def __init__(self, label, category):
        self.label = label
        self.category = category


def main():

    my_dictionary = {'A': 1, 'B': 2}
    print "{}".format(type(my_dictionary))

    poops = {
        (label, Poop(label, category))
        for label, category in DATA['A']
    }

    print "{}".format(type(poops))
    for _, poop in poops:
        print "{}".format(type(poop))


if __name__ == "__main__":
    main()

Output:

pydev debugger: process 1008 is connecting

Connected to pydev debugger (build 191.6605.12)
<type 'dict'>
<type 'set'>
<type 'instance'>
<type 'instance'>
<type 'instance'>
<type 'instance'>

Process finished with exit code 0

Upvotes: 0

Views: 42

Answers (1)

ernest
ernest

Reputation: 161

Because you're using a tuple in your comprehension so it's creating a set of tuples {(k,v)} where k and v are keys and values.

I think what you want is:

poops = {label:Poop(label, category) for label, category in DATA['A'].items()}

The main difference being {k:v for ...} vs {(k,v) for ...}

Upvotes: 1

Related Questions