如何將字典串列轉換為串列?
這是我所擁有的:
{
"sources": [
{
"ID": "6953",
"VALUE": "https://address-jbr.ofp.ae"
},
{
"ID": "6967",
"VALUE": "https://plots.ae"
},
{
"ID": "6970",
"VALUE": "https://dubai-creek-harbour.ofp.ae"
}]}
這是我想要的樣子:
({'6953':'https://address-jbr.ofp.ae','6967':'https://plots.ae','6970':'https://dubai-creek-harbour.ofp.ae'})
uj5u.com熱心網友回復:
這確實非常簡單:
data = {
"sources": [
{
"ID": "6953",
"VALUE": "https://address-jbr.ofp.ae"
},
{
"ID": "6967",
"VALUE": "https://plots.ae"
},
{
"ID": "6970",
"VALUE": "https://dubai-creek-harbour.ofp.ae"
}]
}
然后:
data_list = [{x["ID"]: x["VALUE"]} for x in data["sources"]]
這與以下內容相同:
data_list = []
for x in data["sources"]:
data_list.append({
x["ID"]: x["VALUE"]
})
編輯:您在問題中說轉換為“串列”,這讓我感到困惑。那么這就是你想要的:
data_dict = {x["ID"]: x["VALUE"] for x in data["sources"]}
這與以下內容相同:
data_dict = {}
for x in data["sources"]:
data_dict[x["ID"]] = x["VALUE"]
PS 好像你在這里詢問你的課程作業或其他東西的答案,這不是這個地方的用途。
uj5u.com熱心網友回復:
使用熊貓的解決方案
import pandas as pd
data = {
"sources": [
{"ID": "6953", "VALUE": "https://address-jbr.ofp.ae"},
{"ID": "6967", "VALUE": "https://plots.ae"},
{"ID": "6970", "VALUE": "https://dubai-creek-harbour.ofp.ae"},
]
}
a = pd.DataFrame.from_dict(data["sources"])
print(a.set_index("ID").T.to_dict(orient="records"))
輸出到:
[{'6953': 'https://address-jbr.ofp.ae', '6967': 'https://plots.ae', '6970': 'https://dubai-creek-harbour.ofp.ae'}]
uj5u.com熱心網友回復:
這應該有效。
Dict = {
"sources": [
{
"ID": "6953",
"VALUE": "https://address-jbr.ofp.ae"
},
{
"ID": "6967",
"VALUE": "https://plots.ae"
},
{
"ID": "6970",
"VALUE": "https://dubai-creek-harbour.ofp.ae"
}]}
# Store all the keys here
value_LIST = []
for item_of_list in Dict["sources"]:
for key, value in item_of_list.items():
value_LIST.append(value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444677.html
