【发布时间】:2020-07-31 08:28:20
【问题描述】:
Hi,我想在我的电报机器人上创建按钮,这取决于列表'[“洛杉矶”,“纽约”]'。我对 python dict 有问题,当我将它插入循环时,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)
【问题讨论】:
-
Python 字典(或任何语言中的任何键/值数据结构)中的键是唯一的,因此每次将值映射到键时,它都会发生变异。你问的是这个吗?
-
强烈建议不要使用'dict'作为变量名,因为这会覆盖内置。
标签: python json dictionary element