簡體   English   中英

如何從元組動態更新 python 中的字典值

[英]how to update the values of a dictionary dynamically in python from a tuple

我今天想了一個小練習 python,有人會如何從元組動態更新數組中的字典值。

我有以下字典:

people = [
 {"first_name": "Jane", "last_name": "Watson", "age": 28},
 {"first_name": "Robert", "last_name": "Williams", "age": 34},
 {"first_name": "Adam", "last_name": "Barry", "age": 27}
]

現在我有一個元組列表:

new_names = [("Richard", "Martinez"), ("Justin", "Hutchinson"), ("Candace", "Garrett")]

我試過這種方法:

for person in people:
  for name in new_names:
    person["first_name"] = name
    person["last_name"] = name

但這是錯誤的,因為它在任何地方都給我相同的價值觀

[{'age': 28,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')},
 {'age': 34,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')},
 {'age': 27,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')}]

我如何用上面的元組數據更新first_namelast_name

你的例子:

for person in people:
  for name in new_names:
    person["first_name"] = name
    person["last_name"] = name

正在將name分配給每個字典,因為它嵌套在for person in people的下面。 我建議單步執行您的代碼以查看發生了什么。

它還為整個元組分配了first_namelast_name 您需要執行以下操作:

person["first_name"] = name[0]
person["last_name"] = name[1]

此示例解決了這兩個問題:

for d, name in zip(people, new_names):
    # Assuming the length of new_names and people is the same
    d["first_name"] = name[0]
    d["last_name"] = name[1]
[{'age': 28, 'first_name': 'Richard', 'last_name': 'Martinez'},
 {'age': 34, 'first_name': 'Justin', 'last_name': 'Hutchinson'},
 {'age': 27, 'first_name': 'Candace', 'last_name': 'Garrett'}]

zip創建一個迭代器(tuple-ish),它被解壓用於並行迭代多個變量

SO 中的zip示例

W3 上的zip

暫無
暫無

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

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