I have a list that could contain 1 or many elements. The code below works fine if it has multiple elements in the list. However, if there is only one element, it breaks it into character list.
my_dict = {fruit: ['apple', 'banana', 'carrot']}
li = my_dict.get('fruit')
for fruit in li:
print fruit
Even when there is only one element, it will be treated as a single item in a list as long as you enclose it in square brackets. So this:
my_dict = {'fruit': ['apple']}
will work as you expect, while this:
my_dict = {'fruit': 'apple'}
will not.
(Also, the names of your dictionary keys (e.g. fruit) should be quoted, since they're not variables.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With