簡體   English   中英

Python 3 - 字典理解 Scope -> object -> 列表理解

[英]Python 3 - Scope of dict comprehension -> in object -> in list comprehension

我最近在 Python 3.x 中遇到了這個問題,由於找不到解決方案,我正在尋找有關如何正確解決它的說明。

list_of_dicts = [dict_a, dict_b]
dict_a = {"id": 123, "foo": "bar"}
...

基於字典列表,我想創建另一個列表。

這個列表應該包含某種對象,然后我會用它來做一些事情,在我的例子中是批量寫入數據庫,這按預期工作:

operations = [ Object(arg = {"id": doc["id"]}) for doc in list_of_dicts ]
write_to_db(operations)

我的問題如下:在某些情況下,我想向 arg 字典中添加更多的鍵值對:

further_keys = ["foo"]
operations = [ Object(arg = {"id": doc["id"]}.update({i:doc[i] for i in further_keys}))
               for doc in list_of_dicts ]

不幸的是,這失敗了,因為在 dict comp 的上下文中沒有分配“doc”

問題是是否有可能以某種方式將 scope 設置為列表理解?

我不是最先進的編碼員,很高興在這里提出任何有價值的意見

謝謝!

編輯

謝謝,實際上很簡單,不知道為什么我想在這種情況下使用“更新”。 這是一個最小的工作示例:

import pymongo

data = [{"id":1, "map": "DE", "date":"today"}, 
        {"id":2, "map": "FR", "date":"tomorrow"},
        {"id":3, "map": "IT", "date":"yesterday"}]

additional_keys = ["map"]
standard_key = ["id"]
key_tuple = tuple(standard_key + additional_keys)

operations = [ pymongo.operations.ReplaceOne(
               filter={key:doc[key] for key in key_tuple}, 
               replacement=doc, 
               upsert=True) 
               for doc in data ]

其中 - 根據需要 - 產生:

[ReplaceOne({'id': 1, 'map': 'DE'}, {'id': 1, 'map': 'DE', 'date': 
 'today'}, True, None),
 ReplaceOne({'id': 2, 'map': 'FR'}, {'id': 2, 'map': 'FR', 'date': 
 'tomorrow'}, True, None),
 ReplaceOne({'id': 3, 'map': 'IT'}, {'id': 3, 'map': 'IT', 'date': 
 'yesterday'}, True, None)]

非常感謝你們。 我將來會立即制作一個最小的工作樣本!

您可以在列表理解中使用字典理解。 使用答案,您可以構建以下內容:

operations = [ Object(args = {key:doc[key] for key in ("id", "name", "other key") } ) for doc in list_of_dicts ]

寫了這個手機,所以還沒有測試,但你可以用你想添加到args=的更多鍵來填充那個元組

暫無
暫無

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

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