如何将字典键和相应的值写入文件的每一行

时间:2018-11-04 00:42:42

标签: python dictionary

State_Dict = {"Texas": ["San Antonio, Austin, Houston"] ,
    "California": ["San Diego, Los Angeles, San Francisco"],
    "Florida": ["Miami", "Orlando", "Jacksonville"]}

with open("state.txt", "w") as state:
    for key, value in State_Dict:
        state.write(key, value)

目标:我需要以以下格式将键和值写入文本文件:

Texas
San Antonio
Austin
Houston
California
San Diego
Los Angeles
San Francisco
Florida
Miami
Orlando
Jacksonville

到目前为止,我遇到以下错误:

Traceback (most recent call last):
  File "snip/testBed_2.py", line 7, in <module>
    for key, value in State_Dict:
ValueError: too many values to unpack (expected 2)

Process finished with exit code 1

我如何进行这项工作?

1 个答案:

答案 0 :(得分:0)

您可以使用第二个循环如下循环显示您的值。由于您的值是一个包含单个元素的列表,因此您可以使用[0]索引来获取城市名称,然后使用,(逗号)作为分隔符来划分城市。

您的某些列表将所有城市都作为一个字符串,而某些列表则具有单独的城市名称。因此,您可以使用if语句进行检查。 v.strip()从名称中删除空格。

with open("state.txt", "w") as state:
    for key, value in State_Dict.items():
        state.write(key + '\n')
        if len(value) == 1:
            for v in value[0].split(','):
                state.write(v.strip() + '\n')
        else:
            for v in value:
                state.write(v.strip() + '\n')

输出

Texas
San Antonio
Austin
Houston
California
San Diego
Los Angeles
San Francisco
Florida
Miami
Orlando
Jacksonville