Dict python in循环Json仅获取最后一个元素 [英] Dict python in loop Json gets just the last element
问题描述
Hi, i would like to create buttons on my telegram bot, which depend by the list '["Los Angeles","New York"]'. I have problem with the python dict, when i insert it in a loop, json gets just the last element (New York). Someone can explain me why?
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)
推荐答案
正如其他人在评论中提到的那样,强烈建议不要使用导致问题的原因在其他依赖它的代码中.在下面的代码段中,我使用的名称是listb
而不是dict
.
As mentioned by others in comments, it is strongly advised NOT to use a builtin name as a variable name (for example dict
in the question code) as it can cause issues in other parts of code that depend on it. In the snippet below, I have used the name listb
instead of 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
变量指向一个全新的字典,并丢弃旧值.因此,仅保留了最后一个值.
This line: dict = {"text": i}
does not add a key to dict
, it points dict
variable to an entirely new dictionary and discards old value. So only the last value is retained.
在这种特殊情况下,Telegram API期望包含多个字典的列表,每个字典都在该位置带有键"text"
.
In this particular case, the Telegram API expects a list of multiple dictionaries each with the key "text"
in that place.
这篇关于Dict python in循环Json仅获取最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!