python 字典嵌套 有一对键值为字符串 输出


# lianxi 6-9
favorite_places = {
    "wanglong":"chengdu",
    "sunning":['nanjing','beijing'],
    "yangwei":['tianjing','sichuan','xizang'],
}
for people,places in favorite_places.items():
    print(f"The {people.title()} want go following places:")
            #= {favorite_places[people]}
    for place in places :
        print("\n" + f'{place.title()}')

这第一个为什么会这样?为啥不像后两个    小白求大佬给个解决办法

The Wanglong want go following places:           

C

H

E

N

G

D

U
The Sunning want go following places:

Nanjing

Beijing
The Yangwei want go following places:

Tianjing

Sichuan

Xizang

"wanglong":["chengdu"]   这样写

因为你如果"wanglong":"chengdu"写,这个places就是字符串,第二个for循环就相当于遍历字符串了。所以打印出来是单个字母,"sunning":['nanjing','beijing']写,这个places就是列表,第二个for循环就遍历列表,打印出来就你想要的结果,你也可以这样写,判断places是不是字符串,是的话就直接打印,不是的话就遍历:

favorite_places = {
    "wanglong": "chengdu",
    "sunning": ['nanjing', 'beijing'],
    "yangwei": ['tianjing', 'sichuan', 'xizang'],
}
for people, places in favorite_places.items():
    print(f"The {people} want go following places:")
    # = {favorite_places[people]}
    if type(places)==str:
        print(places)
    else:
        for place in places:
            print("\n" + f'{place}')