Python 拼接C#字典格式对象
依据一个Excel中的2列创建一个字典格式的数据。
例如:
将这2类字符串复制到文本中,读取文本内容,按行读取,每行按空格分隔。
with open(r'D:\TestPoint.txt')as f:
for l in f:
print(l, end='')
这样就按行读取了数据,使用split方法风格。
with open(r'D:\TestPoint.txt')as f:
for l in f:
temp = l.split()
print("{", '"', temp[0], '"', ',"', temp[1], '"}', ',')
输出格式如下:
{ " 2302 " ," A "} ,
{ " 2303 " ," B "} ,
{ " 2304 " ," C "} ,
{ " 2305 " ," RLED "} ,
{ " 2306 " ," YLED "} ,
{ " 2307 " ," BAT "} ,
{ " 2308 " ," TEM-1 "} ,
{ " 2309 " ," Current "}
也使用名称为字典的键,更换位置即可:
print("{", '"', temp[1], '"', ',"', temp[0], '"}', ',')
输出:
{ " A " ," 2302 "} ,
{ " B " ," 2303 "} ,
{ " C " ," 2304 "} ,
{ " RLED " ," 2305 "}
也可以使用TestPointDataID为主键,自建自增变量为值
i =0
with open(r'D:\TestPoint.txt')as f:
for l in f:
temp = l.split()
print("{" +'"' + temp[0] +'"' +',' +str(i), '}' +',')
i = i +1
输出:
{"2302",0 },
{"2303",1 },
{"2304",2 },
{"2305",3 },
{"2306",4 },
{"2307",5 },
{"2308",6 }
在C#中创建字典,直接将输出的字典格式复制过去即可,依据需求可设置键和值的类型:
Dictionary<string, int> TestPointIndex_Dict = new Dictionary<string, int>()
{
{"2302",0 },
{"2303",1 },
{"2304",2 },
{"2305",3 },
{"2306",4 },
{"2307",5 },
{"2308",6 },
{"2309",7 }
}