Home > Enterprise >  Creating a dictionary in python by condition
Creating a dictionary in python by condition

Time:12-17

I want to get a dictionary from an available numeric list, divided by digits and their number in a string.

My inputs:

num_list = list('181986336314')

I need to get a dictionary like this:

mydict = {1: 111, 2: None, 3: 333, 4: 4, 5: None, 6: 66, 7: None, 8: 88, 9: 9}

CodePudding user response:

One way to do it like this way-

from collections import Counter

num_list = list('181986336314')

# Use the Counter class to count the occurrences of each digit in the list
counts = Counter(num_list)

# Initialize an empty dictionary
result = {}

# Iterate over the counts and add the digit and its count to the dictionary
for digit, count in counts.items():
    result[digit] = int(str(digit) * count)

# set None to missing keys
for i in range(10):
    if str(i) not in result:
        result[i] = None

# convert keys to int(optional step: added to match the expected results)
result = {int(k):v for k,v in result.items()}
print(result)

Output:

{1: 111, 8: 88, 9: 9, 6: 66, 3: 333, 4: 4, 0: None, 2: None, 5: None, 7: None}

CodePudding user response:

One way to do it is to post engineer your counter result

counter = Counter(num_list)
my_dict = {}
for i in range(1, 10):
    if (str(i) in counter.keys()):
        my_dict[i] = int(str(i) * counter[str(i)])
    else:
        my_dict[i] = None
    
print(my_dict)

CodePudding user response:

You could keep the digit string as a string and use a dictionary comprehension:

from collections import Counter
s = '181986336314'
c = Counter(s)
{d:d*c[d] for d in '0123456789'}

Resulting dictionary:

{'0': '', '1': '111', '2': '', '3': '333', '4': '4', '5': '', '6': '66', '7': '', '8': '88', '9': '9'}
  • Related