【问题标题】:Ensure unique values within sub elements of a json element while converting from csv从 csv 转换时确保 json 元素的子元素中的唯一值
【发布时间】:2019-07-06 14:36:28
【问题描述】:

我在这里使用答案将我的 csv 转换为 python 中的 json。

How to convert CSV file to multiline JSON?

虽然每个 json 字段都是唯一的。我不确定如何确保每个子 json 字段都有一个唯一元素列表。

例如:

fieldnames = ("domains","ip_address")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
     jsonfile.write('\n')

基本上我想确保 ip_address 列表中的所有项目都是唯一的。 如果是下面显示的列表:

{"ip_address":"x,y,x"}

应该是:

{"ip_address":"x,y"}

我知道如何从列表中获取唯一值。我想知道如何在执行 json 转储时访问此列表。

【问题讨论】:

  • 您能否展示您的尝试并描述它是如何失败的?
  • 提供一个期望输出的例子

标签: python json csv


【解决方案1】:

试试这个:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ...]

unique_list = []
for word in my_list:
    if word not in unique_list:
        unique_list.append(word)

希望对你有帮助 谢谢

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多