Я искал решение в течение нескольких часов, но не могу найти ничего, что могло бы помочь. У меня проблема с преобразованием списка кортежей в словарь. Я получаю эту ошибку: 'ValueError: элемент последовательности обновления словаря # 320 имеет длину 1; 2 требуется. ' Вот небольшой пример списка кортежей:
[('Heat_equation', 262), ('Portal:Tertiary_Educatio', 262), ('Help:Wiki_markup_example', 262), ('Quantum_mechanics', 262), ('IB_Language_A:_English_Language_and_Literature_Course_Materia', 261), ('Pulmonary_Plethor', 261)]
Это то, что я хочу:
{'Heat_equation': 262, 'Portal:Tertiary_Educatio': 262, 'Help:Wiki_markup_example': 262, 'Quantum_mechanics': 262, 'IB_Language_A:_English_Language_and_Literature_Course_Materia': 261, 'Pulmonary_Plethor': 261}
Длина равна 2, хотя верно? Я не уверен, почему я получаю ошибку. Вот функция, в которой я пытаюсь преобразовать список кортежей в словарь:
import urllib.request
import json
import re
def get_url(url):
text = urllib.request.urlopen(url).read().decode()
return text
def get_choice():
try:
print("Select from the following options or press <?> to quit:")
print("1. Display top 1000 articles and views.")
print("2. Display top 100 learning projects.")
choice = input()
choice = int(choice)
if 1 <= choice <= 2:
print()
return choice
except ValueError:
if choice == "":
return None
print("%s is not a valid choice.\n" % choice)
def display_json(text):
lst = []
dictionary = json.loads(text)
for item in dictionary['items']:
for article in item['articles']:
line = (article['article'], article['views'])
lst.append(line)
return lst
def convert_dict(lst):
d = dict()
[d[t[0]].append(t[1]) if t[0] in (d.keys())
else d.update({t[0]: [t[1]]}) for t in lst]
dictionary = {k: v[0] for k, v in d.items()}
return dictionary
def display_dict(dictionary):
print(dictionary)
def learning_project(dictionary):
lst_2 = []
for key, value in dictionary.items():
string = str(key)
match = re.findall(r'([^\/ ]+).*?\w+.*', string)
match.append(value)
tup = tuple(match)
lst_2.append(tup)
return lst_2
def convert(lst_2):
p = dict(lst_2)
print(p)
def main():
while True:
url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
choice = get_choice()
if choice == None:
break
elif choice == 1:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
display_dict(dictionary)
elif choice == 2:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
lst_2 = learning_project(dictionary)
convert(lst_2)
main()
Чтобы объяснить функцию учебного проекта, у меня был больший словарь, который мне нужно было проанализировать. Поэтому я превратил ключ в строку и проанализировал ключ с помощью RegEx. Затем я добавил значение к ключу, и это создало ряды списков. Затем я превратил ряды списков в кортежи и создал список кортежей. Сейчас я просто пытаюсь превратить это обратно в словарь, но он не работает. Любая помощь с благодарностью!