Python中以字符串作为键和字典作为值的映射

2024-10-03 21:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名java开发人员,对python的知识有限

目前,我有一个用例需要用python创建一个映射,其中包含如下条目:

{Name:Shivanshu,TV:LG,Fridge:"LG"}
{Name:Watson,TV:LG,Fridge:"LG"}
{Name:Rohan,TV:BrandA,Fridge:"BrandB"}
{Name:Rohan,WashingMachine:BrandA,CricketBat:"BrandC"}
{Name:Shivanshu, WashingMachine:BrandD, CricketBat:"BrandC"}

在java中,我可以使用

map<String, map<String, String>>

我想创建&;read&;用python编写这样的映射,我知道,我可以使用字符串作为键&;字典作为价值。但是有人能用代码解释一下吗,我们如何在python中利用像这样的customMap

输出:-

{Shivanshu,[TV:"LG",Fridge:"LG",WashingMachine:"BrandD", CricketBat:"BrandC"]}
{Rohan,[TV:"BrandA",Fridge:"BrandB",WashingMachine:"BrandA", CricketBat:"BrandC"]}
{Watson,[TV:"LG",Fridge:"LG"]}

我如何读取文件:

with open('file.txt','r') as records:
    for eachRecord in records:
        Name = eachRecord.split("Name:",1)[1].split(",",1)[0]
        if(eachRecord.find("TV")!=-1):
            TV = eachRecord.split("TV:",1)[1].split(",",1)[0]
        if(eachRecord.find("Fridge")!=-1):
            Fridge = eachRecord.split("Fridge:",1)[1].split(",",1)[0]
        if(eachRecord.find("WashingMachine")!=-1):
            WashingMachine = eachRecord.split("WashingMachine:",1)[1].split(",",1)[0]
        if(eachRecord.find("CricketBat")!=-1):
            CricketBat = eachRecord.split("CricketBat:",1)[1].split(",",1)[0]
        # Here i want to create map & put all corresponding values in map .
        #Here i want to just store this map in another file.

谢谢


Tags: namemapiffindtvsplitlgfridge
1条回答
网友
1楼 · 发布于 2024-10-03 21:36:37

尚不清楚您的文件是否为json格式

我想不会吧

import json

data = []
with open('file.txt', 'r') as records:
    for line in records:
        formatted_line = line.replace('"', '').replace(
            '{', '{"').replace('}', '"}').replace(':', '":"').replace(',', '","')
        data.append(json.loads(formatted_line))

print(data)

这样,数据将成为字典列表(连续数组)

假设您始终有一个名称,并且没有重复的名称,那么最终结果应该如下所示:

dict_ = dict()

for x in data:
    dict_[x['Name']] = {'TV': x['TV'], 'Fridge': x['Fridge']}

print(dict_)

你的问题仍然不清楚。我会试试看

相关问题 更多 >