HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModerate

Convert dict entries to sets and lists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dictconvertlistsandsetsentries

Problem

Can you please tell me if there is a better way to do this?

people = {'123456':{'first': 'Bob', 'last':'Smith'},
          '2345343': {'first': 'Jim', 'last': 'Smith'}}

names = list()
first_names= set()
last_names = set()
for device in people:
    names.append(device)
    first_names.add(people[device]['first'])
    last_names.add(people[device]['last'])


I want to get a list of IDs, and sets of first and last Names. I know this code will work, but can I improve this?

Solution

Instead of appending the id's one by one, I would use:

ids = list(people.keys())


Note that I changed names to ids, as numbers don't seem like names to me. This is something that @jano's answer included but didn't explicitly state.

Then you can change your the rest of your code to:

first_names = set()
last_names = set()

for details in people.values():
     first_names.add(details['first'])
     last_names.add(details['last'])

Code Snippets

ids = list(people.keys())
first_names = set()
last_names = set()

for details in people.values():
     first_names.add(details['first'])
     last_names.add(details['last'])

Context

StackExchange Code Review Q#61024, answer score: 10

Revisions (0)

No revisions yet.