0

This question maybe is meaningless. We always create a list by only one line,like

Onelist = [ _ for _ in range(5)]

to create a list 0-4.

If I want to create a dictionary Result:

CountList = ["zero","one","two","three","four","five","six","seven","eight","nine"]
Result = {
    "zero":0,
    "one":0,
    # each value is zero
xxxxx
}

Is there a pythonic way to do this?

Kevin Mayo
  • 1,089
  • 6
  • 19

4 Answers4

2

You can create dictionaries in the similar way you create lists using list comprehension:

CountList = ["zero","one","two","three","four","five","six","seven","eight","nine"]
Result = {count: 0 for count in CountList}
Sabareesh
  • 711
  • 1
  • 7
  • 14
1

Try:

Result=dict(zip(CountList, [0]*len(CountList)))

Outputs:

{'zero': 0, 'one': 0, 'two': 0, 'three': 0, 'four': 0, 'five': 0, 'six': 0, 'seven': 0, 'eight': 0, 'nine': 0}
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
1

That is quite simple:

dic={k:0 for k in CountList }
Raghul Raj
  • 1,428
  • 9
  • 24
1

There's a function for that...

>>> dict.fromkeys(CountList, 0)
{'zero': 0, 'one': 0, 'two': 0, 'three': 0, 'four': 0, 'five': 0, 'six': 0, 'seven': 0, 'eight': 0, 'nine': 0}
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65