簡體   English   中英

如何從python中的字典中獲取值?

[英]How to get values from dictionary in python?

我想為typeString entity_id with attribute添加entity_id with attribute值。 下面是代碼的詳細信息:

entities =  [{'id': 'Room1',
             'temperature': {'value': '10', 'type': 'String'}, 
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346348'}, 

            {'id': 'Room2',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346664'},

            {'id': 'Room3',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Array',
             'time_index': '2020-08-24T06:23:37.346664'}]

attr = ['temperature','pressure']

self.logger.warning(msg.format( attr, entity_id)

我如何添加id值,其中類型為String並在上面的代碼中帶有warning msg.format .. 新來的 python 所以任何幫助都會很棒。謝謝

要獲取字典鍵的值,請執行以下操作。

dict = {'a':1, 'b':2}
print(dict['a'])

這將打印結果 1

如果您在字典中有字典,請執行以下操作

dict = {1: {'a': 'abc', 'b': 'xyz'}}
print(dict[1][a])

這將打印 abc

將字典放入字典的另一種替代方法是讓特定的鍵保存一個元組,請看以下示例

dict = {'a': ('abc', 'xyz'), 'b':('qwe', 12)}

for i in dict:
    print(dict[i][1])

這將遍歷您的字典並打印 xyz 和 12。您還可以給出一個條件,僅當它符合特定年齡時才打印它。

如果您願意,您還可以遍歷嵌套的字典。

根據您的需要,您可以讓它包含字典或元組,但是,我認為元組使代碼更易於閱讀和理解(這是我的偏好)。

暫無
暫無

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

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