简体   繁体   中英

Create a specialized dictionary from a text file

I have a list of header files and values in a txt file I would like to read and in and write into a dictionary. Where the name is the key and the 0 or 1 is the value.

The format of the txt file looks like:

#define NAME 0
#define MOREOFTHESAME 1

the names are all different lengths but the values are all either 0 or 1. I also want to strip the #define from each line.

Simply split the line at each space, and ignore the 1st enrty:

with open('myFile.txt', 'rb') as fil:
    myDict = {}
    for line in fil:
        _, key, value = line.split()
        myDict[key] = value

You can use dict here, dict expects a sequence with key value pairs. You can split the lines using str.split and pass the last two items using list slicing to dict .

with open('abc') as f:
    dic = dict(line.split()[1:] for line in f)

>>> print(dic)
{'NAME': '0', 'MOREOFTHESAME': '1'}

Example of str.split :

>>> strs = "#define MOREOFTHESAME 1"
>>> strs.split()
['#define', 'MOREOFTHESAME', '1']
>>> strs.split()[1:]
['MOREOFTHESAME', '1']

Using a dict-comprehension(works in py2.7+):

with open('abc') as f:
    dic = {k:v for k,v in (line.split()[1:] for line in f)}
...     
>>> dic
{'NAME': '0', 'MOREOFTHESAME': '1'}

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