[英]how to make one dictionary from several arrays. PYTHON
我想用循環中的幾個 arrays 制作一本字典
a = ["hello","hi"]
b = ["day","night"]
#And these arrays were transformed into a dictionary
c = {"a": "hello, hi", "b": "day, night"}
dictt = dict.fromkeys(a, b)
print(dictt)
你想要的是一個以變量名作為鍵的字典,列表的內容連接在一起作為值。
檢索變量名稱並將它們用作鍵是不常見的,因此您可以像這樣手動執行此操作:
a = ["hello","hi"]
b = ["day","night"]
c = {
'a': ', '.join(a),
'b': ', '.join(b)
}
print(c) # {'a': 'hello, hi', 'b': 'day, night'}
如果你想遍歷 a 和 b 的分配,我會以不同的方式組織 a 和 b。 所以你可以遍歷它們。 像這樣:
# here are your many lists
data = [
["hello","hi"],
["day","night"]
]
# here you go over all the lists and use the index as key
c = {}
for i, lst in enumerate(data):
c[i] = ', '.join(lst)
print(c) # {0: 'hello, hi', 1: 'day, night'}
如果您需要字典鍵是一些字符串,您可以在數據旁邊使用鍵列表:
# define keys
keys = ['a', 'b']
# here are your many lists
data = [
["hello","hi"],
["day","night"]
]
# here you go over all the lists and use the key for keys
c = {}
for i, lst in enumerate(data):
c[keys[i]] = ', '.join(lst)
print(c) # {'a': 'hello, hi', 'b': 'day, night'}
如果您想避免使用鍵列表,但確實想要一些字母作為鍵。 您可以通過字母表來查找鍵。 這限於您可以 go 超過的字母數量:
# here are your many lists
data = [
["hello","hi"],
["day","night"]
]
# here you go over all the lists and use the alphabet letters in order as keys
c = {}
for i, lst in enumerate(data):
c[chr(i+97)] = ', '.join(lst)
print(c) # {'a': 'hello, hi', 'b': 'day, night'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.