Dict python in loop Json 只获取最后一个元素
Dict python in loop Json gets just the last element
嗨,我想在我的电报机器人上创建按钮,这取决于列表'["Los Angeles","New York"]'。我对 python 字典有疑问,当我将它插入循环时,json 只获取最后一个元素(纽约)。有人可以解释一下为什么吗?
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["Los Angeles","New York"]
for i in lista:
dict = {"text": i}
print(dict)
keyboard = {"keyboard": [[dict]]}
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if content_type == "text":
bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)
MessageLoop(bot, handle).run_as_thread()
while 1:
time.sleep(10)
正如其他人在评论中提到的,强烈建议不要使用依赖于它的 builtin name as a variable name (for example dict
in the question code) as it can cause issues in other parts 代码。在下面的代码片段中,我使用了名称 listb
而不是 dict
.
我想你想要的是这个:
lista = ["Los Angeles","New York"]
listb = []
for i in lista:
listb.append({"text": i})
print(listb)
keyboard = {"keyboard": [listb]}
解释:
这一行:dict = {"text": i}
没有向 dict
添加键,它将 dict
变量指向一个全新的字典并丢弃旧值。所以只保留最后一个值。
在这种特殊情况下,Telegram API 需要一个包含多个字典的列表,每个字典在那个地方都有键 "text"
。
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["Los Angeles","New York"]
for i in lista:
dict = {"text": i}
print(dict)
keyboard = {"keyboard": [[dict]]}
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if content_type == "text":
bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)
MessageLoop(bot, handle).run_as_thread()
while 1:
time.sleep(10)
正如其他人在评论中提到的,强烈建议不要使用依赖于它的 builtin name as a variable name (for example dict
in the question code) as it can cause issues in other parts 代码。在下面的代码片段中,我使用了名称 listb
而不是 dict
.
我想你想要的是这个:
lista = ["Los Angeles","New York"]
listb = []
for i in lista:
listb.append({"text": i})
print(listb)
keyboard = {"keyboard": [listb]}
解释:
这一行:dict = {"text": i}
没有向 dict
添加键,它将 dict
变量指向一个全新的字典并丢弃旧值。所以只保留最后一个值。
在这种特殊情况下,Telegram API 需要一个包含多个字典的列表,每个字典在那个地方都有键 "text"
。