Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If dict().fromkeys() all point to the same object, what purpose does the default value argument serve?

The dict method {}.fromkeys() takes an iterable of strings, which will be transformed into dictionary keys. The default value will default to None. For instance:

d = {}.fromkeys(['loss', 'val_loss'])
{'loss': None, 'val_loss': None}

An optional, second argument is the default value that all these values will take:

d = {}.fromkeys(['loss', 'val_loss'], [])
{'loss': [], 'val_loss': []}

I understand that you can initialize an empty dict like this. Where it gets more complicated is that the default values point to the same object.

[id(val) for val in d.values()]
[140711273848032, 140711273848032]

If you would append one list, it would append all the values of this dict. Therefore, you need to re-assign the values to a new object in order to treat the dict values as separate objects:

d['loss'] = list([0.2, 0.4])

If you don't do that, you will change all dict values at the same time.

My question: what purpose is the optional default value intended to serve?

As I see it, you will need to reassign this default value anyway, unless you want to manipulate the same object with different dict keys. I can't think of an honest reason to have many dict keys for one object.

like image 769
Nicolas Gervais Avatar asked Oct 26 '25 10:10

Nicolas Gervais


1 Answers

This can work ( dictionary comprehension)

keys = {'A', 'B', 'C'}
int_lst = [9]
a_dict = { key : list(int_lst) for key in keys }
print(a_dict)
a_dict['B'].append(12)
print(a_dict)
like image 57
balderman Avatar answered Oct 28 '25 01:10

balderman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!