简体   繁体   中英

Cannot convert list of tuples into a dictionary

I've been searching for a solution for hours, but I can't find anything that helps. I'm having a problem converting a list of tuples into a dictionary. I get this error: 'ValueError: dictionary update sequence element #320 has length 1; 2 is required.' Here is a small example of the list of tuples:

[('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)]

This is what I want:

{'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}

The length is 2 though right? I'm not sure why I'm getting an error. Here is the function where I'm trying to convert the list of tuples into a dictionary:

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

To explain the learning project function, I had a bigger dictionary I needed to parse. So I turned the key into a string and parsed the key with RegEx. I then appended the value to the key and that created rows of lists. Then I turned the rows of lists into tuples, and created a list of tuples. Now I'm just trying to turn this back into a dictionary, but it is not working. Any help is greatly appreciated!

data = [('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)]
mydict = dict(data)

if you are getting errors with p = dict(lst_2) then your input data is not compliant with your requirement. You could make the conversion more robust by ensuring that list elements are always a two entry tuple.

p = dict( (*t,None,None)[:2] for t in lst_2 or [])

This will not fix the data but it may allow you to move forward and perhaps detect the faulty data by finding None key or None values in the resulting dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM