Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent breaking of a string into a character list?

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
like image 301
Alex Avatar asked Dec 08 '25 19:12

Alex


1 Answers

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.)

like image 104
B. Shefter Avatar answered Dec 11 '25 07:12

B. Shefter



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!