如何对字典中的值进行迭代?

时间:2019-06-05 06:21:18

标签: python

我是新程序员。我的代码需要帮助。在代码中,我有一个字典,它的值是一个列表。我想在“ while”中做些事情,直到字典具有值为止。我使用了while(len(migration))!= 0,但这是不正确的。如何对字典中的所有值进行迭代? 最后,我想删除字典中的值,但是我不知道该怎么做并更新字典的值。

migration_p = {2: [3, 4], 3: [3]}
def q_sequence():
    global p, sequence_q, r_s, d_s, d, partition, migration_p
    while len(migration_p) != 0:
        sequence_qi = []
        migration_pi = copy.deepcopy(migration_p)
        while len(migration_pi) != 0:
            tqi_min = math.inf
            for p in migration_pi.keys():
                # if len(migration_pi[p]) < M - A:
                for d in migration_pi[p]:
                    for r_src in migration_pi.keys():
                        if r_src not in sequence_qi:
                            xx = time_qi(d, p)[0]
                            if xx < tqi_min:
                                tqi_min = xx
                                r_s = r_src
                                d_s = d
            sequence_qi.append([(time_qi(d, p)[1], d_s), r_s])
            migration_pi = {p: d for p, d in migration_pi.items() if p != r_s}
            migration_pi = {p: d for p, d in migration_pi.items() if (p != r_s or d != d_s)}

        sequence_q.append(sequence_qi)
        # print(sequence_q)
        break

    return sequence_q

我希望输出为[[[(1, 3), 2], [(1, 3), 3]]],但实际输出为[[[(1, 3), 2], [(1, 3), 3], [(2, 4), 2]]]

4 个答案:

答案 0 :(得分:3)

迭代值

for value in dictionary.values():
    ...

答案 1 :(得分:0)

知道有一种内置的方法可以遍历字典中的所有条目是否有帮助?

我记不清了,但这是

的作用
for key in nameOfDictionary:
    print(nameOfDictionary[key])

然后,如果您在完成所有迭代工作之后,可以通过执行以下操作使其删除字典。

for key in nameOfDictionary:
    print(nameOfDictionary[key])
del nameOfDictionary

(可选)如果希望字典仍然存在,则可以使用nameOfDictionary.clear来简单地删除所有条目。

答案 2 :(得分:0)

执行此操作以检索键和值对

for key, value in yourDictionary:
    print "this is key : "+key
    print "this is value : "+value

答案 3 :(得分:0)

for key in migration.keys():
    print "Key: " + key
    print "Value " + migration.pop(key) # This will delete the key from your dict and return a value
    migration[key] = new_value # This will create the key again and update it's value