Apr-02-2018, 07:44 AM
(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 Hawafrom 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