Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

OrderedDict question.

Hello,

Im confused how an OrderedDict that was converted to a list becomes a class dict again when I do for loop for each item.

Example:

def csv_to_list ():
    with open("students.csv", newline="") as csv_file:
        csv_reader = csv.DictReader(csv_file)
        item_list = list(csv_reader)
        return csv_list

def sort_students(students):
    for student in students:
        print(type(student))
#Meaning I can use dict methods when I use for loops.

def sort_students(students):
    smart = []
    for student in students:
        if student["IQ"] == "HIGH":
            smart.append(student)
#Now it is appended back to a list, it becomes a list again.

How can I access that list again like a dictionary if lets say there are more than 2 key,values inside? If I try to do a dict(smart), it gives me an error saying expected values is 2 only. something like this.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

It's no obvious how you are calling these functions, but I think I see the confusion.

Creating a list object from an OrderedDict object results in a list of the dictionary keys:

OrderedDict
>>> d = OrderedDict()
>>> d
OrderedDict()
>>> d[1]="a"
>>> d
OrderedDict([(1, 'a')])
>>> d[2]="b"
>>> d
OrderedDict([(1, 'a'), (2, 'b')])
>>> cvs_list = list(d)
>>> type(cvs_list)
<class 'list'>
>>> cvs_list
[1, 2]

A for loop operates on any container. If the container is a dict then a list of the dict keys are looped over:

for item in some_dict:

# is equivalent to

for item in some_dict.keys():

Post back if you need more help. Good luck!!!