简体   繁体   中英

Converting a file into a dictionary with one key and multiple values

I have a data file that looks like this:

I want to make the first column into a key and the values that come after the key into values of a dictionary.

This is the code I used but it didn't give me what I wanted.

with open('data.txt', 'r') as f:
    ...: 
    ...:     for line in f:
    ...:         items = line.split()
    ...:         key, values = items[0], items[1:]
    ...:         my_dict[int(key)] = values

Assuming you're trying to concatenate additional values from lines with the same key instead of overwriting them, you could use:

for line in f:
    items = line.split()
    key, values = int(items[0]), items[1:]
    my_dict.setdefault(key, []).extend(values)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM