将字符串列表转换成字典

时间:2018-09-21 09:17:15

标签: python list dictionary

我想将字符串列表转换成字典。

在我将其拆分为单独的单词后,列表看起来像这样:

[['ice'], ['tea'], ['silver'], ['gold']]

我想将其转换为如下形式的字典:

{ 1 : ['i', 'c', 'e'] 
  2 : ['t','e','a']
  3 : ['s','i','l','v','e','r']
  4 : ['g','o','l','d']}

到目前为止,这是我的代码:

import itertools

def anagram1(dict):
    with open('words.txt', 'r') as f:
        data = f.read()

        data = data.split()

        x = []

        y = []

        for word in data:
                x1 = word.split()
                x.append(x1)

        for letters in word:
            y1 = letters.split()
            y.append(y1)
            d = dict(itertools.zip_longest(*[iter(y)] * 2, fillvalue=""))

我收到以下错误:

TypeError: 'dict' object is not callable

2 个答案:

答案 0 :(得分:0)

import pprint
l = [['ice'], ['tea'], ['silver'], ['gold']]
d = {idx: list(item[0]) for idx, item in enumerate(l, start =1)}
pprint.pprint(d)
{1: ['i', 'c', 'e'],
 2: ['t', 'e', 'a'],
 3: ['s', 'i', 'l', 'v', 'e', 'r'],
 4: ['g', 'o', 'l', 'd']}

答案 1 :(得分:-1)

以下应做的工作:

with open('file.txt', 'r') as f:
    data = f.read()

data = data.split()

data_dict = {i:v for i,v in enumerate(data)}