0

When my first lists has repeating values, it causes the merge to fail for some reason.

names = ['bob', 'bob', 'bob', 'bob']
id = ['15', '12', '19', '20']
rating = ['100', '90', '100', '80']

dictionary = dict(zip(names, zip(id, rating)))

print(dictionary)

will output

{'bob': ('20', '80')}

However, if I simply change all the names to be unique, it will output as expected.

names = ['bob', 'sally', 'john', 'jill']
id = ['15', '12', '19', '20']
rating = ['100', '90', '100', '80']

dictionary = dict(zip(names, zip(id, rating)))

print(dictionary)

same code with unique names now outputs

{'bob': ('15', '100'), 'john': ('19', '100'), 'sally': ('12', '90'), 'jill': ('20', '80')}

What can I do better than "dict(zip(names, zip(id, rating)))" so I can repeat 'bob' as much as I want?

  • 6
    you can't repeat keys in a dict, that's the whole point – SuperStew Jan 30 '20 at 17:34
  • I believe this is because dictionaries are expected to have a non-repetitive key, otherwise it's impossible to discriminate which value is needed when calling a key that's repeated in the dictionary. Your key should be `id` and not `name` in this scenario. – Celius Stingher Jan 30 '20 at 17:35
  • oooh, thank you! Sorry, I'm learning. my "id" will always be unique, so I'll make that be the key instead. – badsomething Jan 30 '20 at 17:38
  • [Does this post help?](https://stackoverflow.com/questions/10664856/make-a-dictionary-with-duplicate-keys-in-python) – user8314628 Jan 30 '20 at 17:40

2 Answers2

0

Well, unfortunately, you can't use the same key for different values in a dictionary; that would mean that each key would have a different value, which would break the main idea. What I would do instead, if you must have repeating keys, is to change the name according to its position in the original list.

names = ['bob', 'bob', 'bob', 'bob']
id = ['15', '12', '19', '20']
rating = ['100', '90', '100', '80']

new_dict = {}
for i in range(len(names)):
    new_dict[f'{names[i]} #{i}'] = (id[i], rating[i])

You will get a dict consisting of the names in names and their relative positions. This will result in a ListIndex error if you have id or rating shorter than names.

OakenDuck
  • 485
  • 1
  • 6
  • 15
0

you can try this:

a={}
b=[]
for n,i,r in zip(names,id,rating):
  a[n] = (i,r)
  b.append(a)

This will return you a list of dictionary output:

[{'bob': ('20', '80')},
 {'bob': ('20', '80')},
 {'bob': ('20', '80')},
 {'bob': ('20', '80')}]
Shubham Shaswat
  • 1,250
  • 9
  • 14