![](/img/trans.png)
[英]Given a list of [string, number] tuples, create a dictionary where keys are the first characters of strings and the values are sums of the numbers
[英]How to create a dictionary given values and keys as tuples of tuples
我正在嘗試編寫一個 function 代碼,它將創建一個字典給定的值和鍵作為元組的元組。 例如
long2wide ( ((" apple ","red "),(" banana "," yellow "),(" banana "," green "),
(" apple "," green "),(" cherry "," red "))
, (" fruit ", " colour ") )
返回
{'fruit': ['apple', 'banana', 'banana', 'apple', 'cherry'], 'colour': ['red', 'yellow', 'green', 'green', 'red']}
這是我現在擁有的(錯誤的)代碼:
def long2wide(data, headers):
dictionary = {}
for entry in headers:
for i in range(len(data)): #Iterate through each row of data
for j in range(len(data[0])): #Iterate through each column of data
dictionary[(headers)] = data[i][j]
return dictionary
我目前的 output 是 {'fruit': 'red', 'color': 'red'}
:(
如果有人可以幫助調試/解決這個問題,我將不勝感激。 謝謝!!
我是這樣做的:
def long2wide(data, headers):
dictionary = {}
for count, entry in enumerate(headers):
dictionary[entry] = [i[count] for i in data]
return dictionary
output是{' fruit ': [' apple ', ' banana ', ' banana ', ' apple ', ' cherry '], ' colour ': ['red ', ' yellow ', ' green ', ' green ', ' red ']}
當您有未定義數量的標頭時,也可以使用此代碼。
這是通過列表理解完成的。 我們為標題中的每個項目創建一個列表。 然后,我們遍歷數據並為每個數據元組添加一個元素,具體取決於標題的數量,這意味着取決於我們正在迭代的 header。
如果你真的喜歡列表推導,你可以進一步縮小范圍:
dictionary = {entry: [i[count] for i in data] for count, entry in enumerate(headers)}
但我不建議這樣做,因為它會變得凌亂且難以閱讀。
對於任意數量的字段,也許?
def long2wide(values, names):
d = dict()
for i in range(len(names)):
d[names[i]] = [v[i] for v in values]
return d
或者,如果您喜歡單線:
{n: [v[i] for v in values] for i,n in enumerate(names)}
其中values
是您的第一個列表並names
您的第二個列表。
您可以將元組加載到 dataframe 然后回到字典
data=(
(" apple ","red "),
(" banana "," yellow "),
(" banana "," green "),
(" apple "," green "),
(" cherry "," red ")
)
headers= (" fruit ", " colour ")
df=pd.DataFrame(data,columns=headers)
a_dict=df.to_dict()
for key,item in a_dict.items():
print(key)
for i in np.arange(len(item)):
print(item[i])
output:
fruit
apple
banana
banana
apple
cherry
colour
red
yellow
green
green
red
或者您可以直接將數據鍵值對加載到字典中並使用 header 作為索引
headers= ((" fruit ",0),(" colour ",1))
dct = dict((y, x) for x, y in data)
print(dct)
output:
{'red ': ' apple ', ' yellow ': ' banana ', ' green ': ' apple ', ' red ': ' cherry '}
這是一個示例:
def long2wide(data, headers):
dictionary = {}
dictionary[headers[0]] = []
dictionary[headers[1]] = []
for i in data:
dictionary[headers[0]].append(i[0])
dictionary[headers[1]].append(i[1])
return dictionary
那這個呢?
def make_dic(list):
d = {'fruit': [], 'color': [], }
for fruit in long2wide:
d['fruit'].append(fruit[0])
d['color'].append(fruit[1])
return d
long2wide = ((("apple", "red "), ("banana", "yellow"), ("banana", "green"),
("apple", "green"), ("cherry", "red")))
print(make_dic(long2wide))
首先,使用字典推導初始化空列表的字典。
init_dict = {k: [] for k in headers}
然后,遍歷您的元組列表,使每個 output 為 (, )。
for i in data:
# i is the value (<fruit>, <color>)
fruit = i[0]
color = i[1]
init_dict[headers[0]].append(fruit)
init_dict[headers[1]].append(color)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.