我对如何在 python 中使用 PHP 中的命名数组进行了一些研究,同时我发现了以下代码示例,因为他们说可以使用字典来完成。
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
来源:Portion of code getting from here
但是我如何通过循环添加新值?虽然显示如何通过简单地显示 ['key']="value"添加单个值的引用,但我无法链接它们。谁能告诉我如何通过循环将值添加到这个字典中?
例如:
for message in messages:
myvariable inside having two field
- Message
- Phone number
更新 我可以知道如何将它们循环出来以在 aped 列表放入字典后显示吗?谢谢!
最佳答案
您应该将字典添加到数组中,如下所示:
friends = []
for message in messages:
dict = {"message" : message.message, "phone" : message.phone }
friends.append(dict)
要再次循环,您可以这样做:
for friend in friends:
print "%s - %s" % (friend["message"], friend["phone"])
关于python - python中的命名字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14582852/