Табуляция Python дикт - PullRequest
       11

Табуляция Python дикт

0 голосов
/ 18 апреля 2020

Я работаю над созданием клавиатуры на боте телеграммы. Я хотел бы создать несколько кнопок. У меня есть проблема, я хотел бы создать скользящую клавиатуру, которая идет вниз. Есть проблема, с json вы можете создать его с помощью кода n1, но в python я не могу найти решение. Так как же мне конвертировать 'lista = ["New York", "Los Angeles", "Miami", "Toronto", "Berlin", "Rome"]' в json (код n1)?

#code n1 (JSON)
{"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
                         [{"text": "Miami"}, {"text": "Toronto"}],
                         [{"text": "Berlin"}, {"text": "Rome"}]]}


#code2
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]
kdict = []
for i in lista:
    kdict.append({"text": i})
    print(kdict)
keyboard = {"keyboard": [kdict]}



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)

Ответы [ 2 ]

2 голосов
/ 18 апреля 2020

Чтобы связать элементы в списке, вы можете создать итератор из списка, сжать итератор с самим собой и использовать понимание списка для итерации по заархивированным парам:

seq = iter(lista)
[[{'text': i} for i in pair] for pair in zip(seq, seq)]

Возвращает:

[[{'text': 'New York'}, {'text': 'Los Angeles'}],
 [{'text': 'Miami'}, {'text': 'Toronto'}],
 [{'text': 'Berlin'}, {'text': 'Rome'}]]

Затем вы можете преобразовать его в JSON, используя json.dumps.

0 голосов
/ 18 апреля 2020

Использование blhsing ответа

#code n1 (JSON)
{"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
                         [{"text": "Miami"}, {"text": "Toronto"}],
                         [{"text": "Berlin"}, {"text": "Rome"}]]}


#code2
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]

seq = iter(lista)

keyboard = {"keyboard": [[{'text': i} for i in pair] for pair in zip(seq, seq)]}



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)
...