【问题标题】:Dict python in loop Json gets just the last element循环Json中的Dict python只获取最后一个元素
【发布时间】: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


【解决方案1】:

正如 cmets 中的其他人所提到的,强烈建议不要使用 builtin name 作为变量名(例如问题代码中的 dict),因为它可以在 other parts 的代码中使用 cause issues 依赖在上面。在下面的 sn-p 中,我使用了名称 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"

【讨论】:

  • 我强烈建议不要使用dict 作为列表的变量名。
  • @NomadMonad 已修复 (1)。 (我猜我的评论说这是被某人删除了?)
猜你喜欢
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多