将二维列表转换为python中的字典

时间:2013-07-15 05:23:04

标签: python list dictionary readfile

好的,所以我在一个.txt文件的文本文件中读到了这样的格式:

home school 5
home office 10
home store 7
school store 8
office school 4
END OF FILE

然后我把它变成python中的二维列表,它看起来像:

[['home', 'school', '5'], ['home','office','10'],['home','store','7'],
['school','store','8'], ['office','school','4']]

但我真正喜欢它的方式是更多地使用字典格式,例如:

{'home': {'school': 5, 'office': 10, 'store': 7},
'school': {'store': 8},
'office': {'school': 4}}

这种格式看起来好多了,而且更容易阅读。我拥有的数据更详细,但这是简单的版本。我已经阅读了我的文本文件,如下所示:

myFileOpen = open(myInputFile, 'r')
myMap = myFileOpen.readlines()[:-1]

#Format the list, each line becomes a list in a greater list
myMap = [i.split('\n')[0] for i in myMap]
myMap = [i.split(' ') for i in myMap]

如果有人可以帮忙解释如何解释,我将非常感激!谢谢!

4 个答案:

答案 0 :(得分:2)

代码可能如下所示:

result = {}
for item in data:
    result.setdefault(item[0], {}).update({item[1]: item[2]})

使用完整代码证明:http://ideone.com/8XUA41

答案 1 :(得分:1)

跳过中间列表,然后立即执行所有操作:

d = {}

with open(myInputFile, 'r') as handle:
    for line in handle:
        if line == 'END OF FILE':
            continue

        key1, key2, value = line.split()

        if key1 not in d:
            d[key1] = {}

        d[key1][key2] = int(value)

您可以进一步将最后一部分浓缩为:

d.setdefault(key1, {})[key2] = int(value)

答案 2 :(得分:1)

黑客的回答是:

txt =\
'''
home school 5
home office 10
home store 7
school store 8
office school 4
'''

txt = txt.strip()
gs = [line.split(" ") for line in txt.split("\n")]
ts = {}
[ts.setdefault(x, {}).setdefault(y, z) for (x, y, z) in gs]
print ts

答案 3 :(得分:0)

它很乱,但它适用于defaultdict

>>> from collections import defaultdict
>>> L = [['home', 'school', '5'], ['home', 'office', '10'], ['home', 'store', '7'], ['school', 'store', '8'], ['office', 'school', '4']]
>>> d = defaultdict(list)
>>> for i in L:
...     d[i[0]].append(i[1:])
...
>>> {k: dict(v) for k, v in d.items()} # Or d.iteritems with python 2.x
{'home': {'school': '5', 'store': '7', 'office': '10'}, 'school': {'store': '8'}, 'office': {'school': '4'}}

我对使用默认设置没有经验,所以可能有更好的方法。