简体   繁体   English

如何将给定值和键作为元组的元组创建字典

[英]How to create a dictionary given values and keys as tuples of tuples

I'm trying to code a function which would create a dictionary given values and keys as tuples of tuples.我正在尝试编写一个 function 代码,它将创建一个字典给定的值和键作为元组的元组。 Eg例如

long2wide ( ((" apple ","red "),(" banana "," yellow "),(" banana "," green "),
(" apple "," green "),(" cherry "," red "))
, (" fruit ", " colour ") )

returns返回

{'fruit': ['apple', 'banana', 'banana', 'apple', 'cherry'], 'colour': ['red', 'yellow', 'green', 'green', 'red']}

Here's the (erroneous) code I have now:这是我现在拥有的(错误的)代码:

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

My current output is {'fruit': 'red', 'colour': 'red'}我目前的 output 是 {'fruit': 'red', 'color': 'red'}

:( :(

Would really appreciate if anyone could help debug/resolve this.如果有人可以帮助调试/解决这个问题,我将不胜感激。 Thanks!!谢谢!!

This is how I did it:我是这样做的:

def long2wide(data, headers):
    dictionary = {}
    for count, entry in enumerate(headers):
        dictionary[entry] = [i[count] for i in data]
    return dictionary

The output is {' fruit ': [' apple ', ' banana ', ' banana ', ' apple ', ' cherry '], ' colour ': ['red ', ' yellow ', ' green ', ' green ', ' red ']} output是{' fruit ': [' apple ', ' banana ', ' banana ', ' apple ', ' cherry '], ' colour ': ['red ', ' yellow ', ' green ', ' green ', ' red ']}

This code can also be used when you have an undefined number of headers.当您有未定义数量的标头时,也可以使用此代码。

This is done through list comprehension.这是通过列表理解完成的。 We create a list for each item in the headers.我们为标题中的每个项目创建一个列表。 Then, we loop through the data and add one element per tuple of the data, depending on the count of the headers, meaning depending on which header we are iterating through.然后,我们遍历数据并为每个数据元组添加一个元素,具体取决于标题的数量,这意味着取决于我们正在迭代的 header。

If you really liked list comprehensions, you could narrow it down further to:如果你真的喜欢列表推导,你可以进一步缩小范围:

dictionary = {entry: [i[count] for i in data] for count, entry in enumerate(headers)}

But I wouldn't recommend this as it can get messy and hard to read.但我不建议这样做,因为它会变得凌乱且难以阅读。

For any number of fields, maybe?对于任意数量的字段,也许?

def long2wide(values, names):
    d = dict()
    for i in range(len(names)):
        d[names[i]] = [v[i] for v in values]
    return d

Or if you like one-liners:或者,如果您喜欢单线:

{n: [v[i] for v in values] for i,n in enumerate(names)}

where values is your first list and names your second list.其中values是您的第一个列表并names您的第二个列表。

you can load the tuple into a dataframe then back into a dictionary您可以将元组加载到 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: output:

fruit 
  apple 
  banana 
  banana 
  apple 
  cherry 
colour 
  red 
  yellow 
  green 
  green 
  red 

or you can load data key value pairs into a dictionary directly and use the header as an index或者您可以直接将数据键值对加载到字典中并使用 header 作为索引

  headers= ((" fruit ",0),(" colour ",1)) 

  dct = dict((y, x) for x, y in data)        
  print(dct)

output: output:

  {'red ': ' apple ', ' yellow ': ' banana ', ' green ': ' apple ', ' red ': ' cherry '}

here is a sample:这是一个示例:

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

What about this?那这个呢?

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))

First, initialize a dict of empty lists using a dictionary comprehension.首先,使用字典推导初始化空列表的字典。

init_dict = {k: [] for k in headers}

Then, iterate through your list of tuples so that each output is (, ).然后,遍历您的元组列表,使每个 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM