简体   繁体   English

如何将列表中的第一项设置为字典键,并将以下项设置为该键的值?

[英]How to set the first item in a list to a dictionary key, and the following items as the value for that key?

Here is what I'm trying:这是我正在尝试的:

def dict1(filename):
        try:
            file_handle=open(filename,"r")
        except FileNotFoundError:
            return None
        newdict = {}
        for line in file_handle:
            list1 = line.split(",")
            (k, v) = list1
            newdict[k]] = v
        return newdict

The text file has lines like such:文本文件有这样的行:

cow 1,dog 1
john 1,rob 1,ford 1
robert 1,kyle 1,jake 1

I'm trying to create a dictionary like so:我正在尝试创建一个像这样的字典:

{'cow 1': ['dog 1'],
 'john 1': ['rob 1','ford 1'],
 'robert 1': ['kyle 1, 'jake 1']}

The problem is in the (k,v), how can i set the k to the first item in the list, and the v to all items following it?问题出在 (k,v) 中,如何将 k 设置为列表中的第一项,并将 v 设置为后面的所有项?

Using the csv module.使用csv模块。

Ex:前任:

import csv

result = {}
with open(filename) as infile:
    reader = csv.reader(infile)
    for row in reader:           #Iterate each row
        result[row[0]] = row[1:] #column 0 as key and others as value. 

print(result)

Output:输出:

{'cow 1': ['dog 1'],
 'john 1': ['rob 1', 'ford 1'],
 'robert 1': ['kyle 1', 'jake 1']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更新列表中的项,它是字典中键的值? - How to update an item in a list that is value to a key in a dictionary? 如何使用单个键:值对从字典项列表中提取一项? - How can I pull one item, from a list of dictionary items, using a single key:value pair? 将子列表的每个第一项转换为字典键,但第一项是多余的 - Convert each first item of sublist to dictionary key but first items are redundant 在检测到先前已收到字典键作为输入之后,修改列表中该键值的第一项 - After detecting a dictionary key has previously been received as input, modifying the first item in the list that is that key's value 如何使用列表项寻址字典键并附加相应的值 - How to use a list item to address a dictionary key and append the respective value 如何获取字典键列表中第二项的最低值? - How to get the lowest value of second item in key list of dictionary? 如何使用列表的元素来设置字典的键和值? - How do I use elements of list to set the key and value of dictionary? 如何将列表转换为字典,其中第一个列表是键,第二个列表是字典中的值? - how to convert the list to dictionary where first list is key and second list is value in dictionary? 如何从键与列表中的项目匹配的字典中删除键值对? - How to remove key-value pairs from a dictionary where the key matches an item in a list? Python:按取决于第一个键的值划分字典的项目 - Python: DIvide items of a dictionary by a value that depends on the first key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM