Reputation: 11
I have a dict containing 2 key-value pairs, one is a list
dict_special =
{'money' : 100,
'sweets' : ['bonbons','sherbet', 'toffee','pineapple cube']}
I would like to turn the first value into a list also, so I can append items
i.e.
dict_special =
{'money' : [100, 250, 400]
'sweets' : ['bonbons','sherbet', 'toffee','pineapple cube']}
This is what I have tried so far:
newlist = [dict_special['money']]
newlist.append(250)
dict_special['money'] = newlist
But I feel that there must be a more succinct and Pythonic way to get there. Any suggestions?
Upvotes: 0
Views: 170
Reputation: 365925
A more concise way to write this:
newlist = [dict_special['money']]
newlist.append(250)
dict_special['money'] = newlist
… would be:
dict_special['money'] = [dict_special['money'], 250]
However, it's worth looking at why you're trying to do this. How did you create the dict in the first place? Maybe you should have been creating it with [100]
in the first place, instead of 100
. If not, maybe you should have another step for converting the input dictionary (with 100
) into the one you want to use (with [100]
) generically rather than doing it on the fly here. Maybe you even want to use a "multidict" class instead of using a dict directly.
Without knowing more about your code and your problem, it's hard to say, but trying to make these kinds of changes in an ad-hoc way is usually a sign that something is wrong somewhere else in the code.
Upvotes: 2
Reputation: 24788
How about:
newList = {key: value if isinstance(value, list) else [value]
for key, value in dict_special.items()}
Upvotes: 0