根据计数器增加Python字典值 [英] Incrementing Python Dictionary Value based on a Counter

查看:108
本文介绍了根据计数器增加Python字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本重复的字典.

Deca_dict = {
    "1": "2_506",
    "2": "2_506",
    "3": "2_506",
    "4": "2_600",
    "5": "2_600",
    "6": "1_650"
}

我用过collections.Counter来计算每个集合有多少个.

I have used collections.Counter to count how many of each there are.

decaAdd_occurrences = {'2_506':3, '2_600':2, '1_650':1}

然后我创建了一个要更新的新值字典.

I then created a new dictionary of values to be updated.

deca_double_dict = {key: value for key, value in Deca_dict.items()
                        if decaAdd_occurrences[value] > 1}
deca_double_dict = {
    "1": "2_506",
    "3": "2_506",
    "2": "2_506",
    "4": "2_600"
}

(在这种情况下,这是没有最后一项的原始字典)

(in this case, it's the original dict without the last item)

我试图找出如何增加num的值,counter_dict的值减1.这将更新除1之外的所有值,这些值可以保持不变. 目标输出允许其中一个重复项保持相同的值,而其余的将使值字符串的第一个数字递增(基于计数的重复数).我正在尝试为原始Deca_dict表示的数据实现唯一值.

I'm trying to figure out how to increment num, for the values of counter_dict minus 1. This will update all the values except one, which can stay the same. The goal output allows one of the duplicates to keep the same value, whereas the rest will have the first number of the value string incremented increasingly (based on the number of duplicated counted). I'm trying to achieve unique values for the data represented by the original Deca_dict.

Goal output = {'1':'3_506', '2':'4_506', '3':'2_506', '4':'3_600', '5':'2_600'}

我开始按照以下方式进行操作,但最终只增加了所有双精度项,得到的是我原来的值,除了值加一. 对于上下文:发现原始Deca_dict的值将两个数字(deca_address_num和deca_num_route)连接在一起.另外,homesLayer是一个QGIS矢量层,其中deca_address_num和deca_num_route存储在索引为d_address_idx和id_route_idx的字段中.

I started going about things the following way, but ended up just incrementing all double items, resulting in what I had originally, except with values plus one. For context: The values of the original Deca_dict were found concatenating two numbers (deca_address_num and deca_num_route). Also, homesLayer is a QGIS vector layer where deca_address_num and deca_num_route are stocked in fields with indices d_address_idx and id_route_idx.

for key in deca_double_dict.keys():
    for home in homesLayer.getFeatures():
        if home.id() == key:
            deca_address_num = home.attributes()[d_address_idx]
            deca_num_route = home.attributes()[id_route_idx]
            deca_address_plus = deca_address_num + increment
            next_deca_address = (str(deca_address_plus) + '_' +
                                 str(deca_num_route))
            if not next_deca_address in Deca_dict.values():
                update_deca_dbl_dict[key] = next_deca_address

结果无用:

Update_deca_dbl_dict = {
    "1": "3_506",
    "3": "3_506",
    "2": "3_506",
    "5": "3_600",
    "4": "3_600"
}

我的第二次尝试尝试包括一个计数器,但是事情发生在错误的位置.

My second try attempts to include a counter, but things are in the wrong place.

for key, value in deca_double_dict.iteritems():
    iterations = decaAdd_occurrences[value] - 1
    for home in homesLayer.getFeatures():
        if home.id() == key:
            #deca_homeID_list.append(home.id())
            increment = 1
            deca_address_num = home.attributes()[d_address_idx]
            deca_num_route = home.attributes()[id_route_idx]
            deca_address_plus = deca_address_num + increment
            next_deca_address = (str(deca_address_plus) + '_' +
                                 str(deca_num_route))
            #print deca_num_route
            while iterations > 0:
                if not next_deca_address in Deca_dict.values():
                    update_deca_dbl_dict[key] = next_deca_address
                    iterations -= 1
                    increment += 1

更新尽管以下答案之一适用于增加字典中所有重复项,但我仍在尝试重新编写代码,因为我需要将此比较条件与原始数据进行比较为了增加.我仍然有和第一次尝试相同的结果(没用的).

UPDATE Even though one of the answers below works for incrementing all duplicate items of my dictionary, I am trying to re-work my code, as I need to have this comparison condition to the original data in order to increment. I still have the same result as my first try (the useless one).

for key, value in deca_double_dict.iteritems():
    for home in homesLayer.getFeatures():
        if home.id() == key:
            iterations = decaAdd_occurrences[value] - 1
            increment = 1
            while iterations > 0:
                deca_address_num = home.attributes()[d_address_idx]
                deca_num_route = home.attributes()[id_route_idx]
                deca_address_plus = deca_address_num + increment
                current_address = str(deca_address_num) + '_' + str(deca_num_route)
                next_deca_address = (str(deca_address_plus) + '_' +
                                 str(deca_num_route))
                if not next_deca_address in Deca_dict.values():
                    update_deca_dbl_dict[key] = next_deca_address
                    iterations -= 1
                    increment += 1
                else:
                    alpha_deca_dbl_dict[key] = current_address
                    iterations = 0

推荐答案

我认为这可以满足您的需求.我对输入字典进行了一些修改,以更好地说明会发生什么.与您所做的工作的主要区别在于,从Counter字典创建的decaAdd_occurrences不仅可以跟踪计数,还可以跟踪当前地址num前缀的值.这样就可以知道要使用的下一个num值是什么,因为在修改Deca_dict的过程中都会更新下一个num值.

I think this does what you want. I modified your input dictionary slightly to better illustrate what happens. A primary difference with what you were doing is that decaAdd_occurrences, which is created from the Counter dictionary, keeps track of not only the counts, but also the value of the current address num prefix. This makes it possible to know what the next num value to use is since both it and the count are updated during the process of modifying Deca_dict.

from collections import Counter

Deca_dict = {
    "1": "2_506",
    "2": "2_506",
    "3": "2_506",
    "4": "2_600",
    "5": "1_650",
    "6": "2_600"
}

decaAdd_occurrences = {k: (int(k.split('_')[0]), v) for k,v in
                                Counter(Deca_dict.values()).items()}

for key, value in Deca_dict.items():
    num, cnt = decaAdd_occurrences[value]
    if cnt > 1:
        route = value.split('_')[1]
        next_num = num + 1
        Deca_dict[key] = '{}_{}'.format(next_num, route)
        decaAdd_occurrences[value] = next_num, cnt-1  # update values

更新的字典:

Deca_dict -> {
    "1": "3_506",
    "2": "2_506",
    "3": "4_506",
    "4": "3_600",
    "5": "1_650",
    "6": "2_600"
}

这篇关于根据计数器增加Python字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆