簡體   English   中英

如何在python上更新字典?

[英]How to update dictionary on python?

因此,我在運行個人信息查詢時正在創建主詞典。

目前我有:

dictionary = {}
user_input =input('enter user id: ')
D = query(user_input)
dictionary[user_input] = D

如果我打印出dictionary [user_input] = D,我將得到如下信息:

{'user_input':[info]}

我想反復提示並將所有單個信息保存在一個主詞典中,然后將其放入文本文件中。

如何格式化打印件,以便在嘗試將其打印到文本文件時都將其寫成一個大詞典?

我嘗試過的

output_file = ('output.txt', 'w')
print(dictionary, file = output_file)
output_file.close()

這似乎只打印{}

編輯:嘗試了一些差異。 由於D已經返回字典,因此我嘗試:

dictionary.update(D) 

哪個應該將存儲在D中的字典添加到字典中呢?

但是,當我嘗試打印字典時:

print(dictionary)

#it returns: {}

使用json.dump寫入文件。 然后,您可以使用json.load將數據加載回字典對象。

import json

with open('dictionary.txt', 'w') as f:
    json.dump(dictionary, f)

https://docs.python.org/3/library/json.html

編輯:由於您無法使用json也許您可以使用新json問題和答案分開,如下所示。 在以后解析時,這也將很容易且干凈:

with open('dictionary.txt', 'w') as f:
    for k,v in dictionary.items():
        f.write('%s=%s\n' % (k, v,))

對這個問題不是很熟悉,所以我不確定這是否是您要的內容。 但是,您無需打印任務本身即可獲取值。 您可以繼續在字典中添加更多內容,然后將整個字典打印到腳本末尾的文件中,如下所示:

dictionary = {}
user_input =input('enter user id: ')
D = query(user_input)
dictionary[user_input] = D

# do this more times....
# then eventually....

print(dictionary)

# or output to a file from here, as described in the other answer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM