Home > Software design >  How do I use elements of list to set the key and value of dictionary?
How do I use elements of list to set the key and value of dictionary?

Time:02-01

I have to use element 0 of words as a dictionary key and set the value of to_nato for that key to words element 1.

I have this:

natofile = "nato-alphabet.txt"
to_nato = {} #creates empty string
fh = open(natofile) #opens natofile

for line in fh: 
    clean = line.strip()
    lowerl = clean.lower()
    words = lowerl.split()
    to_nato = {words[0]:words[1]}
    print(to_nato)

nato-alphabet is a text file that looks like this:

A Alfa
B Bravo
C Charlie
D Delta
E Echo
F Foxtrot
G Golf
H Hotel
I India

My code returns a list of dictionaries instead one dictionary.

CodePudding user response:

Directly set the key value with dict_object[key] = value:

to_nato[words[0]] = words[1]

This can be written more concisely using the dict constructor and a generator expression.

to_nato = dict(line.strip().lower().split() for line in fh)

CodePudding user response:

Try this:

natofile = "nato-alphabet.txt"
to_nato = {} #creates empty string
fh = open(natofile) #opens natofile

for line in fh: 
    clean = line.strip()
    lowerl = clean.lower()
    words = lowerl.split()
    to_nato[words[0]] = words[1]

fh.close()

print(to_nato)

This sets the element of to_nato with key words[0] to value words[1] for each pair in the file.

CodePudding user response:

dict() can convert any list of pairs of values into a dict

lines=open('nato-alphabet.txt').read().lower().splitlines()
lines = [line.strip().split() for line in lines]
my_dict=dict(lines)
  • Related