如何使用python创建字典列表

时间:2018-04-07 15:19:59

标签: python json list loops dictionary

我有一个函数返回一个列表,我将其序列化为json对象并将其写入JSON文件。

结果是正确的,但问题是它返回分隔列表中的每条记录。

我想要的是返回一个包含多个字典项的列表。

例如:

返回结果:

[{"file Name": "test1.txt", "searched Word": "th", "number of occurence": 1}][{"file Name": "test2.txt", "searched Word": "th", "number of occurence": 1}]

预期结果

[
 {
   "file Name": "test1.txt",
   "searched Word": "th", 
   "number of occurence": 1
  }
  {
   "file Name": "test2.txt",
   "searched Word": "th",
   "number of occurence": 1
  }
 ]

我怎样才能做到这一点?

的代码:

    for counter, myLine in enumerate(textList):
                thematch=re.sub(searchedSTR,RepX,myLine)
                matches = re.findall(searchedSTR, myLine, re.MULTILINE | re.IGNORECASE)


                if len(matches) > 0:  

                    # add one record for the match (add one because line numbers start with 1)
                    d[matches[0]].append(counter + 1)
                self.textEdit_PDFpreview.insertHtml(str(thematch))
                '''
                loop over the selected file and extract 3 values:
                ==> name of file 
                ==> searched expression
                ==> number of occurence 
                '''
listMetaData=[]
                for match, positions in d.items():
                    listMetaData.append({"file Name":fileName,"searched Word":match,"number of occurence":len(positions)})
                jsondata = json.dumps(listMetaData)
                print(jsondata)

6 个答案:

答案 0 :(得分:0)

您可以通过更改保存数据的方式来更改此内容:

listMetaData = []
for match, positions in d.items():
    listMetaData.append({"file Name":fileName,"searched Word":match,"number of occurence":len(positions)})
jsondata = json.dumps(listMetaData)
print(jsondata)

这样你就可以保存

 [{dict: 1}, {dict: 2}]

而不是

[{dict:1}] [{dict: 2}]

答案 1 :(得分:0)

您的代码立即创建一个列表然后打印每个列表。你的问题不清楚你想要什么,但我相信你想要一个所有元数据对象的列表。您可以通过更改代码来实现:

for match, positions in d.items():
            listMetaData = [{"file Name":fileName,"searched Word":match,"number of occurence":len(positions)}]
            jsondata = json.dumps(listMetaData)
            print(jsondata)

all_metadata = []
for match, positions in d.items():
    meta_data = {"file Name":fileName,"searched Word":match,"number of occurence":len(positions)}
    all_metadata.append(meta_data)

json_data = json.dumps(all_metadata)
print(json_data)
return json_data

请注意,python意味着不使用camel case作为变量,而是使用snake case。另外,缩进应该是4个空格(或制表符),而不是10个空格。

答案 2 :(得分:0)

您可以将您的列表合并为new_list = list_1 + list_2

答案 3 :(得分:0)

又快又脏:

您需要在任何for循环之前创建输出列表,从listMetaData变量中删除括号,将listMetaData附加到输出列表,然后移动json.dumps for循环。

<强>解释

因此,您要创建一个list dictionaries。这意味着您需要一个列表来放置任何词典。

您的代码中目前发生的是您使用括号为每个匹配创建列表。

for match, positions in d.items():
        listMetaData = [{"file Name":fileName,"searched Word":match,"number of occurence":len(positions)}]
        jsondata = json.dumps(listMetaData)
        print(jsondata)

尝试在启动for循环之前将列表存储在变量中。然后对结果列表执行json转储。

output_list = []
for match, positions in d.items():
    listMetaData = {"key": value, etc..}
    output_list.append(listMetaData)
jsondata = json.dumps(output_list)
print(jsondata)

答案 4 :(得分:0)

以下是将多个词典列表转换为单个词典列表的示例代码。

我假设您的json以逗号分隔,即每个列表之间都有逗号。

[{"file Name": "test1.txt", "searched Word": "th", "number of occurence": 1}],[{"file Name": "test2.txt", "searched Word": "th", "number of occurence": 1}]

示例代码:

myDict = []
myJsonvar = [{"file Name": "test1.txt", "searched Word": "th", "number of occurence": 1}],[{"file Name": "test2.txt", "searched Word": "th", "number of occurence": 1}]

for idx,jstrings in enumerate(myJsonvar) :
    for inx, elem in enumerate(jstrings) :
        myDict.append(myJsonvar[idx][inx])

print(myDict)

输出

[{'file Name': 'test1.txt', 'searched Word': 'th', 'number of occurence': 1}, {'file Name': 'test2.txt', 'searched Word': 'th', 'number of occurence': 1}]

此输出也将以逗号分隔单个列表词典。

其他方法: 如果您不想制作词典列表或在列表之间添加逗号。

你可以试试这段代码:

import re

import yaml


myListOfDict = []
myJsonvar = '[{"file Name": "test1.txt", "searched Word": "th", "number of occurence": 1}][{"file Name": "test2.txt", "searched Word": "th", "number of occurence": 1}]'

mylist = myJsonvar.split("][")

for lst in mylist :
    updateVar = re.sub(r'[\[\]]', '',lst)
    myListOfDict.append(yaml.load(updateVar))

print(myListOfDict)

<强>输出

[{'file Name': 'test1.txt', 'searched Word': 'th', 'number of occurence': 1}, {'file Name': 'test2.txt', 'searched Word': 'th', 'number of occurence': 1}] 

希望这有帮助

答案 5 :(得分:-1)

[dict1, dict2]

您可以将通常的列表语法与逗号分隔的对象一起使用,其中对象恰好是字典。