Python - 具有相同键的集合词典

时间:2014-10-28 23:57:09

标签: python dictionary set key

我正在尝试创建一个函数来读取每行上有一个单词的文本文件,例如

  

AFD
  asmv
  adsasd

它将使用给定长度的用户的单词并将构造一个python字典,其中键是字母被排序的单词的字符串。值将是具有相同键的所有单词的集合。到目前为止,我有:

def setdict():
wordfile = argv[1]
open(wordfile, "r")
setdict = {}
for line in wordfile:
    words = line.split()
    for word in words:
        word = word.rstrip("\n")
        if word == wordlength:
            key = str(sorted(word))

关于如何使用具有相同键的单词创建集合并将它们放入字典中,我有点迷失。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

collections.defaultdict在这里很有用:

from collections import defaultdict
from pprint import pprint


words = defaultdict(set)

with open('input.txt') as input_file:
    for line in input_file:
        for word in line.split():
            sorted_list = sorted(word)
            sorted_str = ''.join(sorted_list)
            words[sorted_str].add(word)

pprint(words)

当然,您可以使用defaultdict执行任何操作,也可以使用dict.setdefault()

words = dict()
with open('input.txt') as input_file:
    for line in input_file:
        for word in line.split():
            sorted_list = sorted(word)
            sorted_str = ''.join(sorted_list)
            words.setdefault(sorted_str, set()).add(word)

答案 1 :(得分:0)

从简单的事情开始

words = ["hello","python","world"]
my_dict = {}
for word in words:
    try:
       my_dict[sorted(word)].append(word)
    except KeyError:
       my_dict[sorted(word)] = [word]

现在而不是使用预定义的单词从文件中读取它们

  words = map(str.split,open("some_word_file.txt"))

答案 2 :(得分:0)

这里的关键是使用for循环访问字典,使得值集可用于操作。您可以通过逐行读取文件(readline)并检查以下内容来解决您的问题:

for key, value in my_dict:
    if sorted(word) == key:
        value.append(word)
    else:
        my_dict[sorted(word)] = value