Dict python in循环Json仅获取最后一个元素 [英] Dict python in loop Json gets just the last element

查看:509
本文介绍了Dict python in循环Json仅获取最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"> a,您好,我想在我的自动电报bot上创建按钮,具体取决于列表[["Los Angeles","New York"]'.我在使用python dict时遇到问题,当我将其插入循环中时,json仅获取最后一个元素(纽约).有人可以解释我为什么?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆