简体   繁体   中英

How to convert text file into a dictionary in Python

I am trying to take a text file and convert it into a dictionary in Python. The text file has a key/value format to it. When I run my code, I get this error.

Traceback (most recent call last):
File "testCpu.py", line 4, in <module>
(key,val) = line.split()
ValueError: too many values to unpack (expected 2)

Here is my code.

d = {}
with open("/proc/cpuinfo") as f:
    for line in f:
        (key,val) = line.split()
        d[str(key)] = val

print(d)

Here is part of the text file.

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 69
model name  : Intel(R) Core(TM) i3-4030U CPU @ 1.90GHz
stepping    : 1
microcode   : 0x25
cpu MHz     : 1895.570
cache size  : 3072 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 2
apicid      : 0

Can someone please help me with this?

You're close:

key, val = line.split(':') # split into "left" and "right", relative to ":"
key = key.rstrip(' ') # remove whitespaces from the left
val = val.lstrip(' ') # remove whitespaces from the right
# or, use .lstrip(' ') on each to remove whitespaces from both sides

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