[英]How do I use elements of list to set the key and value of dictionary?
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.我必须使用
words
的元素 0 作为字典键,并将该键的to_nato
的值设置为words
元素 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: nato-alphabet 是一个文本文件,如下所示:
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.我的代码返回一个字典列表而不是一个字典。
Directly set the key value with dict_object[key] = value
:直接用
dict_object[key] = value
设置键值:
to_nato[words[0]] = words[1]
This can be written more concisely using the dict
constructor and a generator expression.这可以使用
dict
构造函数和生成器表达式更简洁地编写。
to_nato = dict(line.lower().split() for line in fh)
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.这将文件中每一对的
to_nato
元素的关键字words[0]
设置为值words[1]
。
dict() can convert any list of pairs of values into a dict dict() 可以将任何值对列表转换为字典
lines=open('nato-alphabet.txt').read().lower().splitlines()
lines = [line.strip().split() for line in lines]
my_dict=dict(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.