Dict python in loop Json gets just the last element

。_饼干妹妹 提交于 2020-04-30 06:55:06

问题


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)

回答1:


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.


I think what you want is this:

lista = ["Los Angeles","New York"]
listb = []
for i in lista:
    listb.append({"text": i})
    print(listb)
keyboard = {"keyboard": [listb]}

Explanation:

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.

In this particular case, the Telegram API expects a list of multiple dictionaries each with the key "text" in that place.



来源:https://stackoverflow.com/questions/61278371/dict-python-in-loop-json-gets-just-the-last-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!