python - Python代码中的逻辑问题

标签 python string python-2.7 dictionary

我是 Python 的新手,我正在编写一个简单的程序

输入

{'messagingservice': 'build4', 
 'oltpdatabase': 'build1', 
 'paymentsdatabase': 'build2', 
 'restserver': 'build5', 
 'PESQL': 'build3', 
 'configdatabase': 'build1'} 

预期输出如下

{'build4': 'messagingservice', 
 'build5': 'restserver', 
 'build2': 'paymentsdatabase', 
 'build3': 'PESQL', 
 'build1': 'oltpdatabase,configdatabase '}

下面是我用过的代码...

#!/usr/bin/python
import json
import ast
from sys import argv
data = json.dumps(argv[1]);
json_to_unicode = json.loads(data)
unicode_to_dic = ast.literal_eval(json_to_unicode);
print(unicode_to_dic);
result_dic={};
data='';
for k,v in unicode_to_dic.iteritems():
  if v in result_dic:
    data=data.join((result_dic[v],','));
    print (data)
    result_dic[v]=data

  else:
    result_dic[v]=k;

print(result_dic)

实际输出为:

{'build4': 'messagingservice', 
 'build5': 'restserver', 
 'build2': 'paymentsdatabase', 
 'build3': 'PESQL', 
 'build1': 'oltpdatabase,'}

还缺少一个值。

最佳答案

你可以使用 defaultdict ,这可以使程序更容易:

unicode_to_dic = {
 'messagingservice': 'build4', 
 'oltpdatabase': 'build1', 
 'paymentsdatabase': 'build2', 
 'restserver': 'build5', 
 'PESQL': 'build3', 
 'configdatabase': 'build1'}

from collections import defaultdict

res = defaultdict(list)

# find all keys that have the same value
for key, value in unicode_to_dic.items():
    res[value].append(key)

# convert the list of keys to a string seperated by ','
for key, value in res.items():
    res[key] = ','.join(value)

# Convert it to  a normal dict - that's optional because defaultdict behaves just
# like a normal dict (in most circumstances at least).
dict(res)

# {'build1': 'oltpdatabase,configdatabase',
#  'build2': 'paymentsdatabase',
#  'build3': 'PESQL',
#  'build4': 'messagingservice',
#  'build5': 'restserver'}

我没有调试过你的算法,但有几件事很突出:

  • Python 不需要 ; 在行尾。

  • str.join 实际上称为 seperator.join(list_of_words_to_be_joined)。您使用分隔符作为函数的输入。

关于python - Python代码中的逻辑问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44520223/

相关文章:

python - 用于捕获文件名开头同时编辑文件类型和特定字符集的正则表达式

python - 在Python中的排序字典中查找并计算行中的相同值?

javascript - Solr/Javascript/Python : open source Solr UI with multiple select faceting?

python - R 与 Python 中的 HMAC 编码

python - 插入拼接列表时出现奇怪的行为?

python - replace - 如何替换字符串中最后一次出现的表达式?

c# - 没有小数点的 double 格式

java - 程序无法识别字符串是什么

python - 将列表转换为字符串并返回

python - 使用 ttk.Notebook 小部件从右到左对齐选项卡