Home > Blockchain >  Creating dictionary with duplicate keys from file, having trouble storing list to the key (python 3)
Creating dictionary with duplicate keys from file, having trouble storing list to the key (python 3)

Time:01-16

here is my txt file that has contained all of the lines. What I want to do is create a dictionary, and access a key, and get a list of values

Finance:JPMC
Software:Microsoft
Conglomerate:L&T
Conglomerate:Amazon
Software:Palantir
Defense:BAE
Defense:Lockheed
Software:TCS
Retail:TjMax
Retail:Target
Oil:Exxon
Oil:Chevron
Oil:BP
Oil:Gulf
Finance:Square
FMCG:PnG
FMCG:JohnsonNJohnson
FMCG:Nestle
Retail:Sears
Retail:FiveBelow
Defense:Boeing
Finance:Citadel
Finance:BridgeWater
Conglomerate:GE
Conglomerate:HoneyWell
Oil:ONGC
FMCG:Unilever
Semiconductor:Intel
Semiconductor:Nvidia
Semiconductor:Qualcomm
Semiconductor:Microchip
Conglomerate:Samsung
Conglomerate:LG
Finance:BoA
Finance:Discover
Software:TCS
Defense:Raytheon
Semiconductor:Microsemi
Defense:BAE
Software:Meta
Oil:SinoPec
Defense:Saab
Defense:Dassault
Defense:Airbus
Software:Adobe
Semiconductor:TSMC
FMCG:CocoCola
FMCG:Pesico
Retail:Kohls

Here is my attempted code

f = open("companyList.txt", "r")
sector, company = [], []
for line in f:
    first, second = line.split(":")
    sector.append(first)
    company.append(second)




dictionary = {}


for key in sector:
    for element in company:
        dictionary[sector].append(element)

print(dictionary)

Since there are multiple duplicate keys, I wanted to append a list to that particular key as python doesn't allow duplicate keys.

CodePudding user response:

If i understand your question right you can do this:

from collections import defaultdict

dictionary = defaultdict(list)
for line in f:
    first, second = line.split(":")
    dictionary[first].append(second)

CodePudding user response:

I think this is what you want:

pairs = {}

with open("tst.txt", "r") as f:
    while True:
        line = f.readline().strip()

        if not line:
            break

        sector, value = line.split(":", 1)

        if sector not in pairs:
            pairs[sector] = []

        pairs[sector].append(value)
        
    f.close()

print(pairs)

CodePudding user response:

you should do:

f = open("companyList.txt", "r")
sector, company = [], []
for line in f:
    first, second = line.split(":")
    sector.append(first)
    company.append(second)

dictionary = {}


for sectory,companyy in zip(sector,company):
    dictionary[sectory] = companyy
    
    
    for key in sector:
        dictionary[sector] = key
  •  Tags:  
  • Related