Python Forum
unable to convert text file in dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
unable to convert text file in dictionary
#7
(Mar-29-2018, 12:39 PM)snippsat Wrote: As mention key will be overwritten because of key collision.
Can use defaultdict which can collect values in a list.
Output:
CC_FIPS FULL_NAME_ND AN Aixas AN Aixirivall AN Andorra la Vella AF Biland AF Biland Hawa
from collections import defaultdict

d = defaultdict(list)
with open('to_dict.txt') as f:
    next(f)
    for line in f:
        line = line.strip()
        line = line.split(' '*3)
        if not line == ['']:
            d[line[0]].append(line[1].strip())
Test:
>>> d
defaultdict(<class 'list'>,
            {'AF': ['Biland', 'Biland Hawa'],
             'AN': ['Aixas', 'Aixirivall', 'Andorra la Vella']})
>>> d['AF']
['Biland', 'Biland Hawa']

I was running this code but getting error :
IndexError: list index out of range
Reply


Messages In This Thread
RE: unable to convert text file in dictionary - by purnima1 - Apr-02-2018, 07:44 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 1,365 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Convert File to Data URL michaelnicol 3 1,355 Jul-08-2023, 11:35 AM
Last Post: DeaD_EyE
  Python Script to convert Json to CSV file chvsnarayana 8 2,720 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,212 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Convert Excel file into csv with Pipe symbol.. mg24 4 1,449 Oct-18-2022, 02:59 PM
Last Post: Larz60+
  Need Help: Convert .pcl file to .pdf file ManuRaval 6 2,675 Sep-13-2022, 01:31 PM
Last Post: ManuRaval
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,820 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  convert a named tuple to a dictionary Skaperen 13 3,778 Mar-31-2022, 07:13 PM
Last Post: Skaperen
Question How do I skipkeys on json file read to python dictionary? BrandonKastning 3 2,004 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning
  trying to write a dictionary in a csv file CompleteNewb 13 6,907 Mar-04-2022, 04:43 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020