-1

I would like to create a dictionary based on the keys of another dictionary. Here's the code that I use:

dic2 = {}
dic1 = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
for i in dic1.keys():
    for j in dic1.keys():
        print (i,j)
        dic2[i]=j
print (dic2)

Output :

k1 k1
k1 k2
k1 k3
k2 k1
k2 k2
k2 k3
k3 k1
k3 k2
k3 k3
{'k1': 'k3', 'k2': 'k3', 'k3': 'k3'}

Why all the entries are not added in the dictionary ?

Why don't we have :

dic2 ={'k1':'k1','k1':'k2','k1':'k3','k2':'k1','k2':'k2','k2':'k3','k3':'k1','k3':'k2','k3':'k3'} 

but instead :

dic2 = {'k1': 'k3', 'k2': 'k3', 'k3': 'k3'}  
martineau
  • 119,623
  • 25
  • 170
  • 301
patalvali
  • 105
  • 1
  • 4
  • 8
    Dictionaries must contain a `set` of unique keys. This is because the keys are hashed and used to lookup values. You may benefit from using a `defaultdict(list)` where you can have a single key pointing to a list of values. – JacobIRR Aug 11 '20 at 16:09
  • 1
    @patalvali, as JacobIRR keys are unique, so what is happening is that you are seeing the last value that was assigned to each key. – lmiguelvargasf Aug 11 '20 at 16:11
  • 1
    Quite aside from your script here, try just typing `dic2 ={'k1':'k1','k1':'k2','k1':'k3','k2':'k1','k2':'k2','k2':'k3','k3':'k1','k3':'k2','k3':'k3'}` followed by `print(dic2)`, and see what you get... – alani Aug 11 '20 at 16:12
  • Thank you for your comments. Makes sense. One thing that I still don't understand. Why is it the latest entry that is kept ? It seems more logical to keep the first one (as the others could be considerated as duplicated keys). No ? another point : This question is perhaps duplicated with another one but certainly not with the one that is mentioned. (2 very different questions IMHO) – patalvali Aug 12 '20 at 20:50

2 Answers2

2

Dictionaries must contain a set of unique keys. This is because the keys are hashed and used to lookup values. You may benefit from using a defaultdict with a list factory, instantiated as: defaultdict(list) where you can have a single key pointing to a list of values.

from collections import defaultdict
dic2 = defaultdict(list)
dic1 = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
for i in dic1.keys():
    for j in dic1.keys():
        print (i,j)
        dic2[i].append(j)
print (dic2)

Result:

{'k1': ['k1', 'k2', 'k3'],
 'k2': ['k1', 'k2', 'k3'],
 'k3': ['k1', 'k2', 'k3']}

Note that when we call dic2[i].append(j), the defaultdict creates a new list for you if the current key does not yet point a list to append an item to.

If you do not want to use a defaultdict, you could use dictionary comprehension:

{k: [kk for kk in dic1.keys()] for k in dic1.keys()}
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
1

Dictionary keys have to be unique. You cannot have two "k1" keys for example. In your case, each key keep the value you assigned to it last.

Rowin
  • 435
  • 2
  • 9