簡體   English   中英

如何使用列表的元素來設置字典的鍵和值?

[英]How do I use elements of list to set the key and value of dictionary?

我必須使用words的元素 0 作為字典鍵,並將該鍵的to_nato的值設置為words元素 1。

我有這個:

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 是一個文本文件,如下所示:

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

我的代碼返回一個字典列表而不是一個字典。

直接用dict_object[key] = value設置鍵值:

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

這可以使用dict構造函數和生成器表達式更簡潔地編寫。

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

嘗試這個:

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)

這將文件中每一對的to_nato元素的關鍵字words[0]設置為值words[1]

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM