字典更新序列元素错误 [英] dictionary update sequence element error

查看:55
本文介绍了字典更新序列元素错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有好几个字典文件,我想用这段代码打开每个文件并把它加到一个集合中,以便以后比较和匹配.基本上我有所有可能字符的所有排列的不同列表,我需要知道排列是否在字典中.但是,当我尝试使用所有字典行进行设置时,出现此错误:

choices = ['s','m','o','k','e','j','a','c','k']def解析(选择):我的集合 = {}对于选择项:文件名 = self.location + "/dicts/%s.txt" % (item)mySet.update(open(filename).read().splitlines())返回我的集合

我收到此错误

错误:字典更新序列元素#0 的长度为4;2 是必需的

另外,我想问一下,是否有可能在不到 1 分钟的时间内运行的两组数据(9 个字符排列和 9 个字典文件列表)之间的比较方法.

我知道已经有关于这个错误的问题,但坦率地说,我是一个初学者,我不明白这些问题与我的代码有什么关系,或者如何修复它.

解决方案

如果你写:

mySet = {}

mySet不是set,而是字典(是的,这很令人困惑).例如:

<预><代码>>>>类型({})<类'dict'>

为了构造一个空集,你应该使用:

mySet = set()

set 确实有一个函数 update ,它将所有添加到集合中的可迭代元素作为输入.另一方面,字典需要可迭代的元组(或字典等)

I have several dictionary files, I want this code to open each file and add it to a set, for later comparison and matching. Basically I have a different list of all permutations of all possible characters and I need to know if permutation is in dictionary. But when I try to make a set with all dictionary lines I get this error:

choices = ['s','m','o','k','e','j','a','c','k']
def parsed(choices): 
    mySet = {}

    for item in choices: 
        filename = self.location + "/dicts/%s.txt" % (item)
            mySet.update(open(filename).read().splitlines())

    return mySet  

I get this error

error: dictionary update sequence element #0 has length 4; 2 is required

Furthermore, I'd like to ask if there's a possible comparison method between two sets of data (9 character permutations, and 9 dictionary files list) that runs in less than 1 minute.

I understand that there are already questions regarding this error, but frankly I'm a beginner and I don't understand how those relate to my code, or how to fix it.

解决方案

If you write:

mySet = {}

mySet is not a set, but a dictionary (yeah that is confusing). For instance:

>>> type({})
<class 'dict'>

In order to construct an empty set, you should use:

mySet = set()

A set indeed has a function update that takes as input an iterable of elements that are all added to the set. A dictionary on the other hand requires an iterable of tuples (or a dictionary, etc.)

这篇关于字典更新序列元素错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆