Creating a dictionary in python by condition

Question:

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}
Asked By: Сергей

||

Answers:

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)
> {1: 111, 2: None, 3: 333, 4: 4, 5: None, 6: 66, 7: None, 8: 88, 9: 9}
Answered By: Emmanuel-Lin

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

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

Resulting dictionary:

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

In this approach I used '' instead of None since that way the values have a consistent type. Furthermore, they all have the same meaning: a string of the given length consisting of the given digit.

Answered By: John Coleman

first of all, I am a first-year student that studies software eng. so this I s what I learn about dictionaries in python

To create a dictionary in Python by condition, you can use a loop and an if statement to check for a condition before adding an item to the dictionary.

Here is an example of how you can create a dictionary that only includes keys that have odd values:

# Create an empty dictionary
dictionary = {}

# Loop through a range of numbers
for i in range(10):
  # If the value is odd, add it to the dictionary
  if i % 2 != 0:
    dictionary[i] = i**2

print(dictionary)  # Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

ou can also use a dictionary comprehension to create a dictionary by condition. For example, the following code creates a dictionary that includes only keys with even values:

dictionary = {i: i**2 for i in range(10) if i % 2 == 0}
print(dictionary)  # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Answered By: Buddhi ashen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.