我是Python的新手,为我的一个项目编写了简单的代码
argv[1]={"configdatabase":"build1","oltpdatabase":"build1","paymentsdatabase":"build1","yccdatabase":"build1"}
argv[2]=test.txt
代码:
#!/usr/bin/python
import json
import ast
from sys import argv
data = argv[1];
fileName=argv[2];
data=data.replace("\\","")
print (data)
data = json.dumps(data)
json_to_unicode = json.loads(data)
unicode_to_dic = ast.literal_eval(json_to_unicode);
print(type(unicode_to_dic));
result_dic={};
data="";
for k,v in unicode_to_dic.iteritems():
if v in result_dic.keys():
data=data.join((result_dic[v],',',k));
print (data)
result_dic[v]=data
else:
result_dic[v]=k;
for key,value in result_dic.iteritems():
with open(fileName,'a') as the_file:
the_file.write(key+':'+value+'\n')
预期o / p :build1:configdatabase,oltpdatabase,paymentsdatabase,yccdatabase
但是得到如下输出:
build1:oltpdatabase,yccdatabaseoltpdatabase,yccdatabase,oltpdatabase,yccdatabasepaymentsdatabaseoltpdatabase,yccdatabaseoltpdatabase,yccdatabase,oltpdatabase,yccdatabasepaymentsdatabase,oltpdatabase,yccdatabaseoltpdatabase,yccdatabase,oltpdatabase,yccdatabasepaymentsdatabaseconfigdatabase
有人可以帮助我在这里做错了吗?
答案 0 :(得分:0)
与javascript不同,你不要在python语句的末尾使用分号。这不是问题,只是一个小小的提示。尝试运行此操作,最后一个打印语句应打印出您需要的内容':build1:configdatabase,oltpdatabase,paymentsdatabase,yccdatabase'
问题是你正在取一个字符串值,添加k,然后将该字符串值附加到原始字符串值。所以它可能看起来像这样。
循环1:
data = ''
result_dic[v] = {'build': 'configdatabase'}
循环2:到目前为止,第3步是毛茸茸的。
data = ''
data after join = 'configdatabase, oltpdatabase'
result_dic[v] = {'build': 'configdatabase, oltpdatabase'}
循环3:
data = 'configdatabase, oltpdatabase'
data after join = 'configdatabase, oltpdatabase, configdatabase, oltpdatabase, paymentsdatabase'
* Because you are joining data => 'configdatabase, oltpdatabase, paymentsdatabase' with result_dic[v] => 'configdatabase, oltpdatabase'
result_dic[v] = {'build': 'configdatabase, oltpdatabase, configdatabase, oltpdatabase, paymentsdatabase'}
我希望这是有道理的。祝你的编码冒险好运!
# !/usr/bin/python
import json
import ast
from sys import argv
data = {
"configdatabase": "build1",
"oltpdatabase": "build1",
"paymentsdatabase": "build1",
"yccdatabase": "build1",
}
fileName = 'test.txt'
result_dic = {}
data_string = ""
for k, v in data.iteritems():
if v in result_dic.keys():
result_dic[v] += ',{0}'.format(k)
else:
result_dic[v] = k
print(result_dic)
for key, value in result_dic.iteritems():
print('{}:{}\n'.format(key, value))
with open(fileName, 'a') as the_file:
the_file.write('{0}:{1}\n'.format(key, value))