![](/img/trans.png)
[英]Python 2: what is the best way to obtain information during an exception?
[英]Best way to obtain information from a dict
我有一個帶有“多層”的字典(我真的不知道如何稱呼它),我只想使用其中的少量信息。 所以繼承人的字典:
{'userTimestamp': 1,
'user': {'id': '20',
'links': {'self': [{'href': 'https://john.com'}]},
'mail': 'john@john.com',
'message': 'Hello world',
'name': 'john'}
}
現在我想通過字典,獲取相關信息(在這種情況下名稱(在用戶中),消息)並將信息寫入新的字典。 在 python 中執行此操作的最有效方法是什么?
我建議如下:
new_dict = {}
new_dict["name"] = dict["user"]["name"]
new_dict["message"] = dict["user"]["message"]
dict
的全部意義在於,鍵查找是人類已知的最有效的事情。 如果您知道自己想要什么項目,則無需“通過”字典 - 只需直接獲取它們即可。
userdict = my_dict["user"]
這也適用於嵌套的dict
,因為在每個步驟中,您將再次返回一個純dict
- 這與外部的一樣有效。
username = my_dict["user"]["name"]
為了從舊的單個項目創建一個新的dict
,只需混合項目檢索和 dict 創建。
my_new_dict = {
'foo' : 'bar',
'user_name' : my_dict["user"]["name"], # this will be 'john'
'user_info' : my_dict["user"], # this will be the dict my_dict["user"]
'user_meta' : {key: my_dict["user"][key] for key in ('name', 'mail')}, # this will be a subset of the dict my_dict["user"]
}
對於真正動態的東西,我會使用這樣的東西。
original_dict = {
'name': "Rahul",
'userTimestamp': 1,
'user': {'id': '20',
'links': {'self': [{'href': 'https://john.com'}]},
'mail': 'john@john.com',
'message': 'Hello world',
'name': 'john'}
}
def get_dict_with_relevant_fields(orig_dict, interesting_fields):
new_dict = {}
for key, value in orig_dict.iteritems():
if key in interesting_fields:
new_dict[key] = value
elif isinstance(value, dict):
new_dict.update(get_dict_with_relevant_fields(value, interesting_fields))
return new_dict
這樣我就可以這樣調用:
get_dict_with_relevant_fields(original_dict, ["id", "name"])
但是,如果您知道數據的確切結構以及有限字段的位置以及它們在結構中的位置。 我總是更喜歡這個:
new_dict = {
'name': original_dict['user']['name']
'message': original_dict['user']['message']
}
更好的是,如果我已經有了上面的效用函數,我將按如下方式使用它:
get_dict_with_relevant_fields(original_dict['user'], ['name', 'message'])
當然,我假設沒有性能消耗,並且可以輕松地使上述功能在性能方面變得更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.