将两个列表转换为动态嵌套字典,然后转换为JSON

时间:2019-02-12 20:51:05

标签: python json list dictionary

我必须浏览“颜色”列表:

list1 = ["red","green","other"]

对于每个,我需要仔细检查每个匹配项:

list2 = ["cherries","rasperries","guava","apple","watermelon","grapes","banana"]

如果list2的条件很好,那么我需要创建一个字典,然后将输出写入JSON文件。

for x in list1:
  print x
  for y in list2:
    if y == criteria:
      myDict = {'list1-item': 'fruit1':'apple'}

我的预期输出如下:

data = {'red': {'fruit1': 'cherries', 'fruit2': 'rasperries', 'fruit3': 'guava'},
      'green': {'fruit1': 'apple'},
      'other': {'fruit1': 'watermelon', 'fruit2': 'grapes', 'fruit3': 'banana'}}

写入JSON

with open("data_file.json", "w") as write_file:
    json.dump(data, write_file)

对根据需要构建动态词典不是很熟悉。

1 个答案:

答案 0 :(得分:1)

喜欢吗?

{ cd ../healthy_data ; for i in *; do echo ${i%.dat}; done; }