我是一名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.
谢谢
尚不清楚您的文件是否为json格式
我想不会吧
这样,数据将成为字典列表(连续数组)
假设您始终有一个名称,并且没有重复的名称,那么最终结果应该如下所示:
你的问题仍然不清楚。我会试试看
相关问题 更多 >
编程相关推荐