gpt4 book ai didi

python - 动态地将数组中的值分配给字典

转载 作者:行者123 更新时间:2023-12-01 04:19:21 25 4
gpt4 key购买 nike

我有一个问题。看起来很简单,但我坚持了下来。

我有两个变量;一种是如下所示的数组:

array = [["a@a.com", 1000], ["b@b.com", 2000], ["c@c.com", 3000]]

另一个是一个字典,如下所示:

dictionary = {"email": None, "actions": None}

现在我正在尝试动态地将值从数组分配给字典并将其包装在数组中。

我的代码如下:

result = {"email": None, "actions": None}
new_log = []
for values in sql_result:
for position in result:
for index in range(0, len(result)):
result[position] = str(values[index])

new_log.append(result)

但是它没有按照我的计划正常工作,我得到了奇怪的结果。

打印时 new_log 看起来像:

print(str(position) + " : " + str(result[position]))

看起来像:

actions : a@a.com
actions : 1000
email : a@a.com
email : 1000
actions : b@b.com
actions : 2000
email : b@b.com
email : 2000
actions : c@c.com
actions : 3000
email : c@c.com
email : 3000

打印new_log:

 [{'actions': '3000', 'email': '3000'}, {'actions': '3000', 'email': '3000'}, {'actions': '3000', 'email': '3000'}, {'actions': '3000', 'email': '3000'}, {'actions': '3000', 'email': '3000'}, {'actions': '3000', 'email': '3000'}]

我的目标是让它看起来像这样:

[{'email': 'a@a.com', 'actions': '1000'}, {'email': 'b@b.com', 'actions': '2000'}, {'email': 'c@c.com', 'actions': '3000'}]

最佳答案

我会做这样的事情

{k:str(v) for k,v in array}

关于python - 动态地将数组中的值分配给字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com