从列表中制作字典 [英] Make dictionary from list
问题描述
所以我创建了一个像这样的列表:
So I created a list like this:
list = [line.strip() for line in open('file.txt','r')]
这是我的列表的一部分.
This is a snippet of my list.
[
'1 2',
'2 3',
'2 3',
'4 3 1',
'3 4',
'5 4 2 1',
'4 4',
'8 3 5 2',
'5 7',
'15 11 8 9 6 3 4',
]
我想创建一个字典,其中第一个数字是键,而后面的数字是值,但是我希望它以int形式出现.
I want to create a dictionary where the first number is the key and the number coming after are values but I want it in int form.
我不知道如何使用字典中涉及的类.
I don't know how to use the classes involved with dictionary.
推荐答案
这应该可以解决问题:
In [3]: arrs = [map(int, line.strip().split()) for line in open('file.txt')]
In [4]: first2rest = dict( (arr[0], arr[1:]) for arr in arrs)
In [5]: first2rest
Out[5]: {1: [2], 2: [3], 3: [4], 4: [4], 5: [7], 8: [3, 5, 2], 15: [11, 8, 9, 6, 3, 4]}
让我们拆开它.这部分将文件中的每一行分割为空格,并将其转换为整数:
Let's take it apart. This part splits up each line in your file on spaces and converts them to ints:
map(int, line.strip().split())
然后,此部分创建该行中第一项到其余项的字典:
Then this part creates the dictionary of the first item in the row to the rest:
first2rest = dict( (arr[0], arr[1:]) for arr in arrs)
但是,正如@SethMMorton指出的那样,由于列出的文件多次包含相同的密钥,因此您将丢失数据.
However, as @SethMMorton pointed out, you will lose data as the file you listed includes the same key multiple times.
这篇关于从列表中制作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!