如何更新/添加列表引用中的字典内部的新/现有内容到一个列表中

huangapple go评论64阅读模式
英文:

How to update/add the new/existing contents of a dictionary inside a list from a list reference

问题

根据动态列表的内容,我需要添加/更新另一个列表中的字典。

list1 = ["data1", "data2", "data3", ..... "dataN"]
list_dict1 = [{"Id": "data1"}, {"Id": "data2"}]

如您所见,list1 包含“N”个项目,这些项目不是静态的,因此项目的值和数量将随时间变化而变化。现在,list_dict1 依赖于 list1 来添加/更新字典数据。目前,list_dict1 中有 data1 的值,要求是自动添加/更新 list_dict1 中的字典,包括来自 list1 的项目数或值。

我可以这样做:

# 例如,如果list1只有一个元素

count = len(list1)
if count == 1:
   list_dict1 = [{"Id": list1[0]}]

# 例如,如果list1只有两个元素

count = len(list1)
if count == 2:
   list_dict1 = [{"Id": list1[0]}, {"Id": list1[1]}] 

# 例如,如果list1有四个元素

count = len(list1)
if count == 4:
   list_dict1 = [{"Id": list1[0]}, {"Id": list1[1]}, {"Id": list1[2]}, {"Id": list1[3]}] 

....

但是这种方式,如果列表中有100个元素,我需要编写100个if条件,并手动更新list_dict1。有没有办法自动根据项目数和来自 list1 的相应项目来编写/更新 list_dict1 呢?

英文:

I have a dynamic list of contents which varies on timely basis. Based on the contents of the dynamic list, I need to add/update the dictionary inside the another list.

list1 = ["data1", "data2", "data3", ..... "dataN"]
list_dict1 = [{"Id" : "data1"}, {"Id": "data2"}]

As you can see the list1 contains "N" number of items which is not static so the value and the quantity of the items will be changed on timely manner. Now, list_dict1 is depending on list1 to add/update the dictionary data. Right now, in list_dict1 have the values for data1 the requirement is to automatically add/update the dictionary inside list_dict1 with the count of items or the values from list1.

I can do it the following way:

# Example if list1 has only one element

count = len(list1)
if count == 1:
   list_dict1 = [{"Id" : list1[0]}]

# Example if list1 have only two elements

count = len(list1)
if count == 2:
   list_dict1 = [{"Id" : list1[0]},{"Id" : list1[1]}] 

# Example if list1 have only four elements

count = len(list1)
if count == 2:
   list_dict1 = [{"Id" : list1[0]},{"Id" : list1[1]},{"Id" : list1[2]},{"Id" : list1[3]}] 

....

but this way, if I have 100 elements in the list I need to write 100 if conditions, and need to manually update the list_dict1 accordingly. Is there anyway to automatically write/update the list_dict1 with the count of items and the respective items from list1

答案1

得分: 1

list_dict1 = [{"Id": l} for l in list1]

你的 if 语句做了什么?

但是我不太明白你试图实现什么。更好地解释一下你的目标可能会有所帮助。

英文:
list_dict1 = [{"Id" : l} for l in list1]

Does exactly what you do with your if statements?

But somehow I don't quite get what you are trying to achieve. It might help to explain your goal somewhat better.

huangapple
  • 本文由 发表于 2023年6月5日 18:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定