10
\$\begingroup\$

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?

\$\endgroup\$

3 Answers 3

7
\$\begingroup\$

The only possible improvement I see is to avoid unnecessary dictionary lookups by iterating over key-value pairs:

ids = list()
first_names = set()
last_names = set()

for person_id, details in people.items():
    ids.append(person_id)
    first_names.add(details['first'])
    last_names.add(details['last'])
\$\endgroup\$
10
\$\begingroup\$

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'])
\$\endgroup\$
4
\$\begingroup\$

Use set comprehension:

first_names = {v['first'] for v in people.values()}
last_names = {v['last'] for v in people.values()}
ids=list(people.keys())
\$\endgroup\$
3
  • \$\begingroup\$ Note that if list comprehension is used for ids (i.e. names), it becomes "ids = [k for k in people.keys()]" \$\endgroup\$
    – rask004
    Jun 29, 2018 at 11:24
  • \$\begingroup\$ Just a note, equivalent formulation uses the explicit "set" constructor: first_names = set(d['first'] for d in people.values()), etc \$\endgroup\$
    – ELinda
    Feb 2, 2020 at 19:38
  • \$\begingroup\$ @ELinda Your expression is not completely equivalent because it creates a generator first which is then iterated to create a set. \$\endgroup\$ Oct 17, 2021 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.