Phil
Phil

Reputation: 14651

Python: How should I reformat this short code block?

I'm new to Python. Have been studying it with courses on udacity and now I am trying to do things to learn further more.

I've created this short code block:

list_a = []
list_b = []
for e in a_list:
    list_a.append(e['a'])
    list_b.append(e['b'])
list_b = set(list_b)

(list_a as well should not contain duplicates but it won't be attempted in first place so no strict need of making it a set as well unless it makes the code better looking and easier to go through)

After looking at this code of mine, it does not seem elegant or Pythonic enough.

My question is, how should I reformat this? I would like to learn the good and right way of doing things.

My goal here is to go through a list called a_list, which contains dictionaries as its items. Then for each item in the dictionary, add the value of key 'a' to a new list called list_a, and do the same for key 'b'. However list of key 'b' should be a set and strictly not to contain any duplicates.

Thank you.

Upvotes: 1

Views: 159

Answers (2)

DSM
DSM

Reputation: 353059

@TimPietzcker gave a fine solution. I should mention though that rather than storing data in variable names like list_a and list_b -- what would you do if you if you had nine keys you wanted to pull out? -- I think it's more pythonic to use another dictionary (Python 2.7+):

>>> list_of_dicts = [{'a': 1, 'b': 10}, {'a': 2, 'b': 20, 'c': 30}]
>>> keep = ('a', 'b')
>>> by_key = {k: {d[k] for d in list_of_dicts} for k in keep}
>>> by_key
{'a': set([1, 2]), 'b': set([10, 20])}

and then instead of list_a, you'd use

>>> by_key['a']
set([1, 2])

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

While this does iterate over a_list twice, you can rewrite it like this:

list_a = [e['a'] for e in a_list]
set_b = {e['b'] for e in a_list}

assuming Python 2.7 or later.

I've chosen the name set_b instead of list_b since we're doing a set comprehension, not a list comprehension in the second line.

If you want to iterate over a_list only once, then you can at least skip one list creation:

list_a = []
set_b = set()
for e in a_list:
    list_a.append(e['a'])
    set_b.add(e['b'])

Upvotes: 3

Related Questions