亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Python中不循環獲取鍵的值

如何在Python中不循環獲取鍵的值

慕斯709654 2022-11-01 17:14:32
我有一個 for 循環,我需要在其中分配從另一個字典中獲取的新鍵的值。我試圖避免 for 循環中的 for 循環。我的第一本字典如下所示:ids = [{'1020': 'ID-2522'}, {'1030': 'ID-2523'}, {'1040': 'ID-2524'}]我正在循環的字典列表如下所示:data = [{'sf_id': '1020', TotalPrice': '504'}, {'sf_id': '1030', TotalPrice': '400'}, {'sf_id': '1040', TotalPrice': '500'}]這是我的for循環:for index, my_dict in enumerate(data):    for key, value in my_dict.items():         new_id = my_dict["sf_id"]         opportunity = ids[new_id]以便它獲取對應的值。期望的輸出是:print(opportunity)ID-2522ID-2523ID-2524
查看完整描述

3 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

假設整個集合中沒有重復鍵,您可以使用reduce將每個 id 字典合并到一個 id 字典中,因此您只需迭代兩個集合一次

from functools import reduce


ids = [{'1020': 'ID-2522'}, {'1030': 'ID-2523'}, {'1040': 'ID-2524'}]

data = [{'sf_id': '1020', 'TotalPrice': '504'}, {'sf_id': '1030', 'TotalPrice': '400'}, {'sf_id': '1040', 'TotalPrice': '500'}]


ids_map = reduce(lambda x, y: x.update(y) or x , ids, {})


for my_dict in data:

  new_id = my_dict["sf_id"]

  opportunity = ids_map[new_id]

  print(opportunity)


查看完整回答
反對 回復 2022-11-01
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

ids是字典列表,而不是字典。這使得查找其中一個鍵的效率非常低,因為您必須遍歷整個列表才能找到它。


因此,第一步是將所有這些小字典合并成一個大字典。


然后,我們可以使用您的預期輸出有效地構建一個列表:


ids = [{'1020': 'ID-2522'}, {'1030': 'ID-2523'}, {'1040': 'ID-2524'}]


data = [{'sf_id': '1020', 'TotalPrice': '504'}, 

        {'sf_id': '1030', 'TotalPrice': '400'}, 

        {'sf_id': '1040', 'TotalPrice': '500'}]


ids_dict = {k:v for dct in ids for k, v in dct.items()}


opportunity = []


for my_dict in data:

    new_id = my_dict["sf_id"]

    opportunity.append(ids_dict[new_id])


print(opportunity)

# ['ID-2522', 'ID-2523', 'ID-2524']

(注意enumerate如果不使用索引就不需要)


或者,更短的,使用列表理解:


opportunity = [ids_dict[my_dict["sf_id"]] for my_dict in data]

print(opportunity)

#  ['ID-2522', 'ID-2523', 'ID-2524']


查看完整回答
反對 回復 2022-11-01
?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

# Create a new variable and save sftoap in it

new_ids = ids


# pop the items from original list of dicts and save it in a new dict 

sftoap_dict = {}

for d in new_ids:

    key, value = d.popitem()

    sftoap_dict[key] = value


查看完整回答
反對 回復 2022-11-01
  • 3 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號