简体   繁体   English

键:从txt文件到字典的值对

[英]Key:Value Pairs from txt file into a dictionary

I have a txt file with key value pairs. 我有一个包含键值对的txt文件。 It can format (get, retrieve) the pairs from the file in multiple ways, for example: 它可以通过多种方式格式化(获取,检索)文件对,例如:

as line separated strings with colons: 作为用冒号分隔的字符串:

stringa1:stringa2
stringb1:stringb2

or as line separated strings with commas: 或用逗号分隔行:

stringa1,stringa2
stringb1,stringb2

or as individuals lists of strings: 或作为单独的字符串列表:

[stringa1,stringa2]
['stringa1','stringa2']

AND, I can assign each string to a variable with: 并且,我可以使用以下命令将每个字符串分配给一个变量:

    for string in list
        splitstring=list.split(',')    
        for item in splitstring:
            print (item)
    >>>stringa1
    >>>stringa2

But I can't figure out how to add those key:value pairs to a dictionary 但是我不知道如何将这些key:value对添加到字典中

d[splitstring[0]] = splitstring[1] 

should work, where d is a dict. 应该可以工作,其中d是字典。 That's the easiest way of adding a key, value pair to a dictionary. 这是将键值对添加到字典中的最简单方法。

Another way is: 另一种方法是:

d.update({splitstring[0]: splitstring[1]})

Taking in mind that we are talking about pairs, then this should work: 考虑到我们正在谈论配对,那么这应该起作用:

mydict = {}
for i in range(0,len(splitstring),2):
    mydict[splitstring[i]] = splitstring[i+1]

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

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