我正在嘗試根據另一個值更新字典串列中的特定專案
我有字典串列
Product_id= [{ "id": 342, "count": 10 },
{"id": 345, "count": 20 },
{"id": 546, "count": 30 },
{"id": 324, "count": 40 },
{"id": 789, "count": 50 },
{"id": 675, "count": 60 }]
我想增加 x "id" 的 "count" 其中 "id" == x
例如,如果“id”== 342 我想將計數增加 1,那么輸出將是
print(Product_id)
[{ "id": 342, "count": 11 },
{ "id": 345, "count": 20 },
{ "id": 546, "count": 30 },
{"id": 324, "count": 40 },
{"id": 789, "count": 50 },
{"id": 675, "count": 60 }]
我可以提出計數,但可以更新()計數......
我已經嘗試了很多東西并搜索了堆疊等(我知道我的最后一次嘗試是遙遙無期,下面)所以任何想法都會受到歡迎
for d in Product_id:
d.update((k 1, "count") for k, v in d.items() if v\["id"\] == 342)
uj5u.com熱心網友回復:
當你有一個listof 時,dictionaries你可以回圈遍歷dictionary. list在此之后,找到id感興趣的(這里是342)。然后count將該字典的 增加1。
您可以這樣做:
Product_id= [{ "id": 342, "count": 10 },
{"id": 345, "count": 20 },
{"id": 546, "count": 30 },
{"id": 324, "count": 40 },
{"id": 789, "count": 50 },
{"id": 675, "count": 60 }]
x = 342
for item in Product_id:
if item["id"] == x:
item["count"] = 1
# You can add a break here if there's only one item to update.
輸出:
[{'id': 342, 'count': 11}, {'id': 345, 'count': 20}, {'id': 546, 'count': 30}, {'id': 324, 'count': 40}, {'id': 789, 'count': 50}, {'id': 675, 'count': 60}]
uj5u.com熱心網友回復:
您需要遍歷整個字典串列并檢查滿足您條件的元素。
for p in Product_id:
if p['id'] == 342:
p['count'] =1
print(Product_id)
uj5u.com熱心網友回復:
我的建議:
for dic in Product_id:
if dic["id"] == id:
dic["count"] = 1
uj5u.com熱心網友回復:
回答:
您的問題在這里有一個非常好的和 pythonic 相關的答案 -->在串列的每個字典中添加一個元素(串列理解)
為了可讀性和撰寫succing/pythonic代碼,我將使用python中的串列理解來解決這個問題:
在 1 行中:
p_id = [{**dct,**{'count':dct[k] 1}} if dct['id']==342 else dct for dct in Product_id]
如果您想要在功能等中使用更具適應性的版本:
# let x be the value that you want to upate
x = 342
# and k be the key of that value
k = 'count'
p_id = [{**dct,**{k:dct[k] 1}} if dct['id']==x else dct for dct in Product_id]
解釋:
- 如果條件為真,則在串列推導中使用
ifelsestatemets 回傳修改后的{'key' : 'value'}對值,如果條件為真,則簡單地回傳字典。- 您不能像 in 那樣從串列 comp 中分配變數
value =1,但是展平形式(同時使用 if 和 else)仍然比非串列理解形式更簡潔。**{}合并到字典,最右邊替換'count'的關鍵vluee pari,這是等效的:
p_id = [dict(dct,**{k:dct[k] 1}) if dct['id']==x else dct for dct in Product_id]
這將產生相同的結果,您可能更喜歡。對于條件為真的最左邊的專案,如果這個 evaluetes 為假,那么 dict 如果簡單地回傳。4.star star **解包字典,見 --> **(雙星/星號)和*(星/星號)對引數有什么作用? 5. 較長形式的 this 等價于:
p_id = [{'id':dct['id'],'count':dct['count'] 1} if dct['id']==x else dct for dct in Product_id]
6 Rightmost item is the for loop itself and replaces:
for item in itterable:
if some_condition:
#do some stuff
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456014.html
