Как подсчитать вхождения и обновить значение словаря? - PullRequest
0 голосов
/ 31 января 2020

Я перебираю столбец базы данных

Мне нужно создать словарь, который обновляет определенные значения определенных ключей, если критерий удовлетворяется.

Например

The first iteration is: 'apples'
The dictionary should be {'apples': 1}

The second iteration is: 'peers'
The dictionary should be {'apples': 1, 'peers': 1}

The third iteration is: 'apples'
The dictionary should be {'apples': 2, 'peers': 1}

Прошу прощения за базовое c объяснение. Это лучший способ (я думаю) передать то, что я хочу, потому что я не знаю, как это кодировать.

Мне нужно, чтобы это было в словаре, потому что эта операция глубоко во вложении для l oop структура

ЦЕЛЬ:

Требуется получить итерацию, которая наиболее подходит

Желаемый результат:

mostListed = 'apples'

Я новичок в python если я упускаю что-то очевидное, я очень открыт для изучения

Ответы [ 5 ]

2 голосов
/ 31 января 2020

Добавим это к уже многочисленным ответам для ясности

from collections import Counter

values = ['apples', 'peers', 'apples']

Counter(values).most_common(1)

>>> [('apples', 2)]
2 голосов
/ 31 января 2020

Без defaultdict

Вы можете использовать следующий код:

d = {}
for iteration in ['first', 'second', 'third']:
    value = input(f'The {iteration} iteration is:')
    if value in d:
        d[value] += 1
    else:
        d[value] = 1

print(d)

Выход:

The first iteration is:apples
The second iteration is:peers
The third iteration is:apples
{'apples': 2, 'peers': 1}

Использование defaultdict

Вы можете создать defaultdict со значением по умолчанию 0 следующим образом:

from _collections import defaultdict
d = defaultdict(lambda: 0)
for iteration in ['first', 'second', 'third']:
    value = input(f'The {iteration} iteration is:')
    d[value] += 1

print(dict(d))

Выход

The first iteration is:apples
The second iteration is:peers
The third iteration is:apples
{'apples': 2, 'peers': 1}
2 голосов
/ 31 января 2020

Использование Counter() из collections:

>>> from collections import Counter
>>> l = ["apples", "pears", "apples"]
>>> Counter(l)
Counter({'apples': 2, 'pears': 1})

Работа в вашем случае идет, например, как:

from collections import Counter

list_ = []

for item in ["first", "second", "third"]:
    input_value = input(f"{item} iteration: ")
    list_.append(input_value)
count = Counter(list_)
print(count) # output: Counter({'apples': 2, 'pears': 1})
print(count.most_common(1)) # output: [('apples', 2)]
1 голос
/ 31 января 2020

Вот пример:

my_list = ['apples', 'apples', 'peers', 'apples', 'peers']
new_dict = {}

for i in my_list:
    if i in new_dict:
        new_dict[i] += 1
    else:
        new_dict[i] = 1

print(new_dict)
0 голосов
/ 31 января 2020

Вы можете обновить значения ключа в словаре, выполнив

if 'apples' in dict:
    dict['apples'] += 1
else:
    dict['apples'] = 1

, и вы можете найти ключ с максимальным значением примерно так:

most_listed = max(dict, key=lambda k: dict[k])
...