簡體   English   中英

字典作為值和索引作為鍵

[英]Dictionary of dictionaries as values and index as keys

我需要從字典中創建一個字典(讓我們將其命名為通用)。 General 是一個字典,它有其他字典作為值和索引(按添加順序)作為鍵。

樣品一般:

{
1: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added first 
2: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added next (second) 
3: {'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}, #was added third and so on 
}

樣本字典:

{'DATE: ': '2021.12.03', 'TIME: ': '01:50:08', 'LAT: ': '41.1905'}

我有一個生成上述字典的 for 循環,我只需要一種方法來 append 到一般使用的鍵,該鍵將是附加字典的順序。

對不起,如果不清楚,我盡力了。

如果要保留插入順序,則應使用列表而不是字典。 自 Python 3.6 起,字典保留插入順序。 但是,這個事實對大多數人來說並不是很明顯,這使您的代碼更難理解,並且如果您運行的 Python 版本早於 3.6,則不能依賴此行為。

所以,你有兩個選擇:

  1. 使用列表並在要添加時調用.append()
  2. 如果您出於某種原因必須使用字典,則general[len(general) + 1] = # dictionary to append的內容將生成您要查找的密鑰。 但同樣,出於上述原因,我會認真建議不要這樣做。

此示例假設您要手動輸入數據:

general = {}
def add_to_dict():
    n = 0
    while True:
        n+=1
        date = input("Enter date: "),
        time = input("Enter time: "),
        lat = input("Enter latitude: ")
        
        general[f'{n}'] = {'DATE':date,'TIME':time,'LAT':lat}

        another = input("Enter another? Y/N: ").capitalize().strip()
        if another == 'Y':
            another = True
            continue
        else:
            print(general)
            break
add_to_dict()

暫無
暫無

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

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