简体   繁体   English

如何在 python 中使用“item”将列表更改为字典?

[英]How I can change a list using 'item' to dictionary in python?

I want to run a code from Github. In the following piece of the code:我想运行来自 Github 的代码。在以下代码段中:

def read_table(table_file):
    
        table = dict()
        
        with open(table_file, 'rb') as handle:
            while True:
                   try:
                           table = pickle.load(handle)
                   except EOFError:
                           break
        
        f_set=set()
        
        for k,v in list.items():
            for feature in v[DATA]:
                f_set.add(feature)
               
        return table , f_set

I got this error: AttributeError: 'list' object has no attribute 'items' How can I change the list to dict in this code?我收到此错误: AttributeError: 'list' object has no attribute 'items'如何在此代码中将列表更改为字典? Can anyone please help me?谁能帮帮我吗?

I try to change the list using filter or dir() function but I got new errors.我尝试使用 filter 或 dir() function 更改列表,但出现新错误。

You're trying to iterate over list .您正在尝试迭代list list is a builtin type in Python. What you probably meant to do is iterate over table , which is a dictionary and does have a .items() method. list是 Python 中的内置类型。您可能想做的是迭代table ,它是一个字典并且确实有一个.items()方法。

Here's the revised snippet:这是修改后的片段:

import pickle

def read_table(table_file):
    table = dict()
    with open(table_file, 'rb') as handle:
        while True:
            try:
                table = pickle.load(handle)
            except EOFError:
                break
    f_set = set()

    for k, v in table.items():
        for feature in v[DATA]:
            f_set.add(feature)

    return table, f_set

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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