-1

So, i've got this code.

old = [8,2,4,3,5,2,6,4,5]
new = dict((i, 0) for i in old)

that's what i get:

{8:0, 2:0, 4:0, 3:0, 5:0, 6:0}

it's like set(). Why dict don't add every item?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35

5 Answers5

2

There is no way to do this, no. Dictionaries rely on the keys being unique - otherwise, when you request or set a key, what value would be returned or overwritten?

What you could do, however, is store a list as the value for the dictionary, and then add your values to that list, rather than replacing the existing value.

You might want to use a collections.defaultdict to do this, to avoid making the lists by hand each time a new key is introduced.

0

In a Python dictionary, no two entries can have the same key. Since your original list contains values which are repeated, they are omitted when you create a dictionary.

Note that because entries in a dictionary are accessed by their key, we can't have two entries with the same key.

This is the reason you cannot have a dictionary containing the same key values.

0

dict is a (key, value) pair where key is unique. By using the same key you "rewrite" the corresponding value (which in your case is just re-affecting 0).

MetallimaX
  • 594
  • 4
  • 13
0

Python dict type uses hashes, so you cannot add a key twice, even with different values each time. So, dict has unique keys. When you set a key twice, Python just replaces its value.

0

if you want to assign unique key to each element then you can write:

`

new={}
  old = [8,2,4,3,5,2,6,4,5]
  for i in range(len(old)):
     new.update({i:old[i]})
  print(new)
  

output: {0: 8, 1: 2, 2: 4, 3: 3, 4: 5, 5: 2, 6: 6, 7: 4, 8: 5}

Mohit Rathore
  • 71
  • 1
  • 4