简体   繁体   English

输出Python词典的内容

[英]Outputting Contents of a Python Dictionary

There are a lot of posts here about outputting the contents of a dictionary. 这里有很多关于输出字典内容的文章。 I actually figured out a non-optimal solution to my problem (as I'll show below), but I'm most interested in why my non-optimal solution worked. 我实际上找到了解决问题的非最佳解决方案(如下所示),但是我对为什么我的非最佳解决方案最感兴趣。

Here is my code: 这是我的代码:

import csv

keys = ("Ev", "E1", "E2", "E3", "I", "B", "O", "T")
p = input("P")
e = input("e")
e2 = input("e2")
e3 = input("e3")
it = input("it")
b = input("b")
o = input("o")
t = input("t")

dictionary = {"Ev": p, "E1": e, "E2": e2, "E3": e3, "I": it, "B":b, "O": o, "T": t}
dictionary2 = {"Ev": p, "E1": e, "E2": e2, "E3": e3, "I": it, "B":b, "O": o, "T": t}

with open("infile.csv", "a") as f:
    w = csv.DictWriter(f, keys)
    w.writeheader()
    for answer in (dictionary, dictionary2):
        w.writerow(answer)

My goal was to just have one dictionary. 我的目标是只拥有一部字典。 But when I tried outputting the contents of the dictionary, I kept getting a ValueError regarding "B". 但是,当我尝试输出字典的内容时,我不断收到与“ B”有关的ValueError。 I tried a few solutions and the best one seemed to be adding a second dictionary which just prints the same exact output twice and I can remove exact duplicates from the output file when I open it. 我尝试了几种解决方案,最好的解决方案似乎是添加第二本字典,该字典仅将相同的确切输出打印两次,并且当我打开输出文件时,可以从输出文件中删除精确的重复项。 I know this is terrible practice, but it was the quickest solution I had and it was a bummer to get caught up in this for a while. 我知道这是很糟糕的做法,但这是我有最快的解决方案,而且在一段时间内陷入困境实在是令人遗憾。

Why does adding a second dictionary work in this case? 为什么在这种情况下添加第二个词典有效? I don't understand why this code throws a ValueError if only one dictionary is used, but when two are it works fine (except for the duplicate line I then have to remove). 我不明白,如果仅使用一个字典,为什么这段代码会引发ValueError,但是当两个字典都可以正常工作时(除了重复的行,我必须删除它)。

EDIT 编辑

The non-working code was the line: 无效的代码是这一行:

for answer in (dictionary):

which, as Martijn kindly points out, just loops over the keys of the one dictionary. 正如马丁(Martijn)所指出的那样,它只是循环浏览一本字典的键。

EDIT2 EDIT2

And, the traceback error is: 而且,回溯错误是:

Traceback (most recent call last):
  File "file.py", line 41, in <module>
    w.writerow(answer)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/csv.py", line 149, in _dict_to_list
    + ", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: B

You created a tuple to loop over: 您创建了一个元组来循环:

for answer in (dictionary, dictionary2):

Before, you probably tried to loop over the dictionary: 以前,您可能试图遍历字典:

for answer in dictionary:

or perhaps: 也许:

for answer in (dictionary):

which won't work; 哪个行不通; you are then looping over just the keys of one dictionary. 然后,您仅遍历一本字典的键。 Since you didn't include the code that didn't work, we can only speculate on that point. 由于您没有包含无效代码,因此我们只能推测这一点。

Either write the one dictionary directly without looping: 要么直接编写一本字典,而无需循环:

w.writeheader()
w.writerow(dictionary)

or use a one-element tuple: 或使用单元素元组:

for answer in (dictionary,):
    w.writerow(answer)

See Tuple syntax to learn why the extra comma is essential there. 请参阅元组语法,以了解为什么在此处必须使用多余的逗号。 Parenthesis around an expression are optional in Python, and just group that expression to span lines or denote precedence; 在Python中,表达式的括号是可选的,并且可以将该表达式分组以跨越行或表示优先级。 you need at least one comma to make it a tuple. 您需要至少一个逗号使其成为一个元组。

On the other hand, a NameError almost always points to a simple typo; 另一方面,一个NameError几乎总是指向一个简单的错字。 perhaps you forgot to quote the "B" key in your dictionary. 也许您忘记在字典中引用"B"键。 Again, without a traceback, this is pure speculation. 同样,没有追溯,这纯粹是猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM