Soulmaster
Soulmaster

Reputation: 111

Python List to Dictionaries

I have started learning python and I have a question. I have a list and I want to convert it to a dictionary. How is it possible?

For example, I have a class:

Person (name, surname, age, country)

I have created many person objects and added them to a list. However, searching in a list takes too long time so I want to create a dictionary. How can I convert this person list to a dictionary?

Thanks

Upvotes: 0

Views: 353

Answers (1)

Robᵩ
Robᵩ

Reputation: 168616

Use a dict comprehension:

# Assusming "person_list" is your list of "Person" objects
name_to_person = { p.name: p for p in person_list }

Usage:

george_details = name_to_person['George']
print "George is %d years old"%(george_detals.age)

Of course, you don't have limit your keys to the members of Person. If you want to look up by a combination of name and surname, for example:

 fullname_to_person = { p.name + ' ' + p.surname: p for p in person_list }

Upvotes: 5

Related Questions