簡體   English   中英

從python中的兩個列表創建字典

[英]Creating a dictionary from two lists in python

我有一個JSON數據如下。

input_list = [["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]]

我還有另一個清單,其中列出了預期的密鑰

list_keys = ['name', 'current_project', 'details']

我正在嘗試使用兩者創建一個dic,以使數據可用於指標

我已經匯總了問題的兩個列表,但是它一直持續下去,列表中有多個元素。 input_list是一個嵌套列表,其中包含500k +個元素,每個list元素具有其自己的70+個元素(請詳細說明)list_keys中也包含70+個元素。

我試圖使用zip創建字典,但鑒於數據的大小,它無濟於事,而且使用zip時,我無法從中排除“詳細信息”元素

我期望輸出這樣的東西。

[
  {
    "name": "Richard",
    "current_project": "",
    "children": "yes",
    "divorced": "no",
    "occupation": "analyst"
    },
  {
    "name": "Mary",
    "current_project" :"testing",
    "children": "no",
    "divorced": "yes",
    "occupation": "QA analyst",
    "location": "Seattle"
    }
]

到目前為止,我已經嘗試過了

>>> for line in input_list:
...     zipbObj = zip(list_keys, line)
...     dictOfWords = dict(zipbObj)
...
>>> print dictOfWords
{'current_project': ['testing'], 'name': 'Mary', 'details': {'location': 'Seattle', 'children': 'no', 'divorced': 'yes', 'occupation': 'QA analyst'}}

但是與此有關,我無法擺脫嵌套的dict鍵“細節”。 所以尋求幫助

people = input_list = [["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]]
list_keys = ['name', 'current_project', 'details']
listout = []
for person in people:
    dict_p = {}
    for key in list_keys:
        if not key == 'details':
            dict_p[key] = person[list_keys.index(key)]
        else:
            subdict = person[list_keys.index(key)]
            for subkey in subdict.keys():
                dict_p[subkey] = subdict[subkey]

    listout.append(dict_p)
listout

使用zip的問題在於, people列表中有該附加詞典。 這將獲得以下輸出,並應在更大的個人列表中起作用:

[{'name': 'Richard',
  'current_project': [],
  'children': 'yes',
  'divorced': 'no',
  'occupation': 'analyst'},
 {'name': 'Mary',
  'current_project': ['testing'],
  'children': 'no',
  'divorced': 'yes',
  'occupation': 'QA analyst',
  'location': 'Seattle'}]

好像您想要的是字典列表,這是我在終端中編碼並復制到此處的內容。 希望能幫助到你。

>>> list_of_dicts = []
>>> for item in input_list:
...     dict = {}
...     for i in range(0, len(item)-2, 3):
...             dict[list_keys[0]] = item[i]
...             dict[list_keys[1]] = item[i+1]
...             dict.update(item[i+2])
...     list_of_dicts.append(dict)
...
>>> list_of_dicts
[{'name': 'Richard', 'current_project': [], 'children': 'yes', 'divorced': 'no', 'occupation': 'analyst'
}, {'name': 'Mary', 'current_project': ['testing'], 'children': 'no', 'divorced': 'yes', 'occupation': '
QA analyst', 'location': 'Seattle'}]

我將提到這不是理想的方法,因為它依賴於input_list中完美排序的項目。

該腳本將遍歷input_list每一項,並創建沒有任何列表或字典的新列表:

input_list = [
    ["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
    ["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]
]

list_keys = ['name', 'current_project', 'details']

out = []
for item in input_list:
    d = {}
    out.append(d)
    for value, keyname in zip(item, list_keys):
        if isinstance(value, dict):
            d.update(**value)
        elif isinstance(value, list):
            if value:
                d[keyname] = value[0]
            else:
                d[keyname] = ''
        else:
            d[keyname] = value

from pprint import pprint
pprint(out)

印刷品:

[{'children': 'yes',
  'current_project': '',
  'divorced': 'no',
  'name': 'Richard',
  'occupation': 'analyst'},
 {'children': 'no',
  'current_project': 'testing',
  'divorced': 'yes',
  'location': 'Seattle',
  'name': 'Mary',
  'occupation': 'QA analyst'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM