0
my_dict = { 1: 11, 2: 12, 3: 13 }

If I want to work on the list of keys from my_dict there appear to be (at least) three ways to do this in Python >3.5 (i.e. on or after PEP 448)

List Comprehension:

[key for key in my_dict]

[1, 2, 3]

Unpacking:

[*my_dict]

[1, 2, 3]

Constructing a list from the view of the keys:

list(my_dict.keys())

[1, 2, 3]

Are these three methods interchangeable?

I think

  • [key for key in my_dict] is the most 'Pythonic',
  • [*my_dict] is the most terse, and
  • list(my_dict.keys()) is the most readable.

Are there any technical reasons for choosing between these?

1 Answer 1

2

These all accomplish the same thing. For the last one, calling keys() is not required. list(my_dict) will do the same thing. It's a little more clear if you call keys() explicitly so you might want to do it anyway.

The rest of this question is opinion-based. While all are valid options, I think 1 & 3 are preferable for this use and #2 makes sense for unpacking into method calls.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.