在Python中遍历字典内部的列表

4

我很新手Python,需要创建一个函数来将字典中列表中的值除以2:

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

期望输出:

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

我发现了这篇文章 python: iterating through a dictionary with list values,对我有些帮助,但是不幸的是,我无法理解其中的"whatever"部分示例代码。
我尝试了以下代码:
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

我写了不同的变体,但在“for j...”行中一直收到KeyError: 0的错误提示。

7个回答

6
那是因为字典(dict)与列表不同,它们不使用索引,而是使用键(就像标签),您可以使用dict.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)

输出:

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

如果你不想要小数点,可以使用//代替/


5

看,理解式的威力:

>>> 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]}

在外层有一个字典推导式,在每个列表中使用一个“内部”列表推导式来分割值。


3

你必须使用键名访问字典中的元素。在此示例中,键名是'A'和'B'。如果你尝试使用整数访问字典,则会导致范围错误。

以下函数可正常工作:

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

这种方法效率低下,因为你需要进行字典查找而不是遍历键值对;此外,你还会在每次迭代时创建和销毁一个临时字典。 - Arya McCarthy

2

你不能像迭代列表那样使用 range(len(dic)) 对字典进行数字迭代(这种方法也不应该用于列表)。这就是为什么 dic[i] 不起作用的原因,因为没有 dic[0]。相反,应该迭代字典的键。

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

诚然,理解列表推导式是更好的方法,但这种方式保留了你所做的形式,并说明了问题出在哪里。


2
为了轻松遍历字典,使用 for key in dictionary。使用列表推导式很容易将列表分成两半。
for k in dic1:
    dic1[k] = [x / 2 for x in dic1[k]]

在函数形式中
def divdict(d):
    for k in d:
        d[k] = [x/2 for x in d[k]]

1

我采用了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()}

获取:

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

1
您可以使用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()}
lambda函数与map相结合,将在字典的每个值上迭代该函数。通过使用字典理解,我们可以将lambda应用于每个值。

在Python 3中,这会返回map对象,而不是列表。这意味着它只能使用一次。当不清楚您是否只会遍历每个列表一次时,请优先选择列表推导式。 - Arya McCarthy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接