【问题标题】:libpostal output string (dict) with duplicate keys and I need to convert string to Dict带有重复键的 libpostal 输出字符串(dict),我需要将字符串转换为 Dict
【发布时间】:2022-01-16 17:36:24
【问题描述】:

我使用libpostal 地址解析库作为.exe 文件。我有一个脚本来读取终端的输出。输出将是 stringdict 格式,如下所示,

这是地址字符串

"531A UPPER CROSS STREETSINGAPORE HONG LIM COMPLEX 051531 S"

libpostal 终端输出是

'{\n  "house_number": "531a",\n  "road": "upper cross streetsingapore",\n  "city": "hong",\n  "house": "lim complex",\n  "house_number": "051531 s"\n}'

我需要从这个字符串创建一个Dict,如果有重复的键,则将值一起附加到同一个键中。

预期输出Dict

{
  "house_number": "531a 051531 s",
  "road": "upper cross streetsingapore",
  "city": "hong",
  "house": "lim complex",
}

帮助将不胜感激

【问题讨论】:

  • 到目前为止你尝试过什么?请显示您的代码的Minimal, reproducible example 以及您当前的输出或错误。
  • 我使用的是eval(dict),但这会跳过重复的键。但是,现在我在这里发布答案后得到了图片。无论如何感谢@JanWilamowski

标签: python json string dictionary parsing


【解决方案1】:

您可以使用json.JSONDecoder 将字典文字解码为元组列表,使用dict.setdefault 将值组合到列表中,最后将字典值中的所有项目连接起来:

string = '{\n  "house_number": "531a",\n  "road": "upper cross streetsingapore",\n  "city": "hong",\n  "house": "lim complex",\n  "house_number": "051531 s"\n}'

from json import JSONDecoder
decoder = JSONDecoder(object_pairs_hook=lambda x: x).decode(string)
out = {}
for tpl in decoder:
    out.setdefault(tpl[0],[]).append(tpl[1])
    
out = {k:' '.join(v) for k,v in out.items()}

输出:

{'house_number': '531a 051531 s',
 'road': 'upper cross streetsingapore',
 'city': 'hong',
 'house': 'lim complex'}

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2013-05-25
    相关资源
    最近更新 更多