Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a dictionary using for loops (python) [duplicate]

I'm trying to create a dictionary using for loops. Here is my code:

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
    for x in values:
        dicts[i] = x
print(dicts)

This outputs:

{0: 'John', 1: 'John', 2: 'John', 3: 'John'}

Why?

I was planning on making it output:

{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Why doesn't it output that way and how do we make it output correctly?

like image 438
Halcyon Abraham Ramirez Avatar asked May 16 '15 21:05

Halcyon Abraham Ramirez


People also ask

Is duplicate allowed in dictionary Python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can we use dictionary in for loop Python?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Can we add duplicate keys in dictionary Python?

Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list.


2 Answers

dicts = {} keys = range(4) values = ["Hi", "I", "am", "John"] for i in keys:         dicts[i] = values[i] print(dicts) 

alternatively

In [7]: dict(list(enumerate(values))) Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} 
like image 144
Ajay Avatar answered Sep 30 '22 06:09

Ajay


>>> dict(zip(keys, values)) {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} 
like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 08:09

Ignacio Vazquez-Abrams