简体   繁体   English

遍历python字典中的列表

[英]Iterate through a list inside a dictionary in python

I'm very new to Python and I need to create a function that divides by 2 the values in the lists inside the dictionary:我对 Python 非常陌生,我需要创建一个函数,将字典中列表中的值除以 2:

dic = {"A":[2,4,6,8], "B":[4,6,8,10]}

desired output:所需的输出:

dic2 = {"A":[1,2,3,4], "B":[2,3,4,5]}

I found this post我找到了这个帖子

python: iterating through a dictionary with list values python:遍历具有列表值的字典

which helped a little, but unfortunately is the "whatever" part of the example code that I can't figure out.这有点帮助,但不幸的是我无法弄清楚示例代码的“任何”部分。

I tried this:我试过这个:

def divide(dic):
    dic2 = {}
    for i in range(len(dic)):
        for j in range(len(dic[i])):
            dic2[i][j] = dic[i][j]/2
    return dic2

I wrote different variations, but I keep getting a KeyError: 0 in the "for j..." line.我写了不同的变体,但我一直在“for j...”行中收到 KeyError: 0 。

That's because dict s aren't like lists, they do not use indices, they use keys (like a label), and you can use dict.keys() to fetch a dict 's keys.那是因为dict不像列表,它们不使用索引,它们使用键(如标签),并且您可以使用dict.keys()来获取dict的键。

Alternatively, just looping through a dict using for in loops through the keys:或者,只需使用for in循环遍历dict键:

dic = {"A": [2, 4, 6, 8], "B": [4, 6, 8, 10]}

for k in dic: # similar to `for key in dict.keys():`
    dic[k] = [x/2 for x in dic[k]]

print(dic)

Output:输出:

{'A': [1.0, 2.0, 3.0, 4.0], 'B': [2.0, 3.0, 4.0, 5.0]}

If you don't want that decimal point, use // instead of / .如果您不想要那个小数点,请使用//而不是/

Behold, the power of comprehensions :看,领悟的力量:

>>> dic = {"A":[2,4,6,8], "B":[4,6,8,10]}
>>> dic2 = {k:[v/2 for v in vs] for k,vs in dic.items()}
>>> dic2
{'A': [1, 2, 3, 4], 'B': [2, 3, 4, 5]}

There is a dict comprehension at the outer level, and an "inner" list comprehension used to divide the values in each list.在外层有一个字典理解,还有一个“内部”列表理解,用于划分每个列表中的值。

You can't necessarily numerically iterate over a dictionary—your range(len(dic)) .您不一定能对字典进行数字迭代——您的range(len(dic)) (You shouldn't iterate over lists that way, either.) That's why dic[i] doesn't work—there's no dic[0] . (您也不应该以这种方式遍历列表。)这就是dic[i]不起作用的原因——没有dic[0] Instead, iterate over its keys.相反,迭代它的键。

def divide(dic):
    dic2 = dic.copy()
    for key, value in dic:
        for i, _ in enumerate(value):  # Enumerate gives the index and value.
            dic2[key][i] = value[i]/2
    return dic2

Admittedly, comprehensions are a better way to go, but this preserves the form of what you did and illustrates where the problem was.诚然,理解是一种更好的方式,但这保留了你所做的事情的形式,并说明了问题所在。

To easily iterate over a dictionary, use for key in dictionary.要轻松迭代字典,请在字典中使用 for 键。 Dividing the list by two is easily done with list comprehension使用列表理解可以轻松地将列表一分为二

for k in dic1:
    dic1[k] = [x / 2 for x in dic1[k]]

in a function form以函数形式

def divdict(d):
    for k in d:
        d[k] = [x/2 for x in d[k]]

You have to access elements of the dictionary using their key.您必须使用它们的键访问字典的元素。 In the example keys are 'A' and 'B'.在示例中,键是“A”和“B”。 You are trying to access the dictionary using an integer and that gives you the range error.您正在尝试使用整数访问字典,这会给您带来范围错误。

The following function works:以下功能有效:

def divide_dic(dic):
    dic2 = {}

    # Iterate through the dictionary based on keys.
    for dic_iter in dic:

        # Create a copy of the dictionary list divided by 2.
        list_values = [ (x / 2) for x in  dic[dic_iter] ]

        # Add the dictionary entry to the new dictionary.
        dic2.update( {dic_iter : list_values} )

    return dic2

You can try this with lambda:你可以用 lambda 来试试这个:

the_funct = lambda x: x/2

dic = {"A":[2,4,6,8], "B":[4,6,8,10]}

new_dict = {a:map(the_funct, b) for a, b in dic.items()}
## for Python 3.5
new_dict = {a:[*map(the_funct, b)] for a, b in dic.items()}

The lambda function is coupled with map, which will iterate the function over every element in the values of the dictionary. lambda 函数与 map 结合使用,它将在字典值中的每个元素上迭代函数。 By using dict comprehension, we can apply the lambda to every value.通过使用 dict comprehension,我们可以将 lambda 应用于每个值。

I used a subtle variation of Wim's answer above (focus is on the comprehension using key ):我使用了上面 Wim 答案的细微变化(重点是使用key的理解):

dic = {"A":[2,4,6,8], "B":[4,6,8,10]}
dic2 = {k:[v/2 for v in dic[k]] for k in dic.keys()}

to get:得到:

dic2
{'A': [1.0, 2.0, 3.0, 4.0], 'B': [2.0, 3.0, 4.0, 5.0]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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