简体   繁体   中英

Why default set in dict with python?

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?

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.

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.

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).

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.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM