[英]python 2.7 2D dictionay
Dict = {}
target = [
['55.0', 'Index', '0', '18512'],
['55.0', 'Index', '0', '18513']]
for input in target:
temperature, hum, out = input[0], input[1], input[2:]
Dict.setdefault(temperature, {}).setdefault(hum, out)
print Dict
我認為結果是{'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0', '18513']}}
但實際結果僅為{'55.0': {'Index': ['0', '18512']}}
我如何解決它?
您要的是字典列表:
list_of_dicts = []
target = [
['55.0', 'Index', '0', '18512'],
['55.0', 'Index', '0', '18513']]
for input in target:
temperature, hum, out = input[0], input[1], input[2:]
list_of_dicts.append({temperature: {hum: out}})
print list_of_dicts
輸出 :
[{'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0','18513']}}]
但是,如果您要使用包含兩個“ '55.0'
鍵和嵌套詞典'hum: out'
的字典,則這是不可能的,因為字典可以具有不固定的鍵,因此您的第二項將始終覆蓋第一個項。
還有一些注意事項:
1.) setdefault()
非常適合在鍵不存在的情況下默認鍵的項目值,但是在您的用例中,由於鍵不是唯一的,因此適得其反,因此每次都會覆蓋該值。 在這種特殊情況下,只需為每個項目創建一個字典,然后在結果list
append()
就足夠了。
2.)盡量避免使用諸如input
或dict
類的保留關鍵字。 盡管您已經大寫了Dict
但還是很容易引入諸如覆蓋某些內置功能的錯誤。 對於Python,建議的命名約定是對變量/屬性使用小寫字母和下划線,對於類使用大寫字母。 在此處閱讀有關文檔的更多信息 。 這只是一個建議,您可以擁有自己的風格。 但是通過遵循一套一致的約定,您的代碼將更易於調試。
from collections import defaultdict
target = [
['55.0', 'Index', '0', '18512'],
['55.0', 'Index', '0', '18513']]
main_dict = []
for tar in target:
key, index, list_ = tar[0], tar[1], tar[2:]
local_dict = defaultdict(dict)
local_dict[key].update({index:list_})
main_dict.append(dict(local_dict))
print(main_dict)
>>>[{'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0', '18513']}}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.