Search code examples
pythonlistpacking

Is there a reason for unpacking a list then putting it back into a list?


I'm trying to understand the following Python line:
result = {'key_A': [*dict_A.keys()], 'key_B': "dummy_string"}
Result is dictionary that holds a list in Result['key_A'] and string in Result['key_b']. But I'm not sure why the dict_A.keys() has to be unpacked, only to be put into a list again. Is there a reason for this extra unpacking operation?


Solution

  • In Python 3 .keys does not return a list, but a dict_keys object, so if list is required it must be converted.

    [*dict_A.keys()] is equivalent to list(dict_A.keys())