簡體   English   中英

將列表轉換為帶有鍵值對的字典

[英]Converting a list into a dictionary with key value pairs

我有一個形式為的 python 列表

scores = [' "abc":1, "xyz":"2", "def":3 ']

我需要將其轉換為 python 字典,以便使用鍵提取字典元素。

scores_dict = { "abc":1, "xyz":"2", "def":3 }

我希望能夠提取 score_dict["abc"] = 1 等。

我參考了下面的鏈接並嘗試了一些示例,但我被卡住了:

Python將列表轉換為具有鍵值的字典

scores_dict = dict.fromkeys(scores, 1)
print(scores_dict["abc"])

dict_comp = {k.strip():v.strip() for k,v in zip(scores[0].split(','), scores[1].split(','))}
print(dict_comp)

def score_parser(scores):
    row = scores.split(',')
    network.append(row)
    return network

好的,所以您要做的是考慮整個列表並將鍵與值分開,然后將其添加到字典中

scores_dict = {}
for thing in scores:
    thing = thing.split(":")
    key = thing[0]
    value = thing[1]
    scores_dict[key] = value
print(scores_dict)

如果它不起作用,請告訴我(我是在電話上輸入的,所以我希望它很好)

您可以使用json

import json

scores = [' "abc":1, "xyz":"2", "def":3 ']

scores_dict = json.loads('{' + scores[0] + '}')

輸出:

{'abc': 1, 'xyz': '2', 'def': 3}

如果你像這樣修改你的列表:

scores = [["abc", 1], ["xyz", 2], ["def", 3]]

您將能夠使用 dict()

dict_scores = dict(scores)

暫無
暫無

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

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