0

**I want combine two lists in one dictionary in complete form ** my code

name_list =[225.85, 286.818, 238.8, 282.43, 238.522, 238.378, 233.989, 294.957, 238.522, 290.847, 238.8, 282.286, 290.847, 282.008, 282.43, 233.989, 225.85, 282.008, 294.957, 282.286, 286.818, 238.378, 229.961]
num_list =[[3, 24, 5, 12], [3, 12, 24, 5], [3, 12, 5, 24], [3, 5, 24, 12], [3, 5, 12, 24], [24, 3, 12, 5], [24, 3, 5, 12], [24, 12, 3, 5], [24, 12, 5, 3], [24, 5, 3, 12], [24, 5, 12, 3], [12, 3, 24, 5], [12, 3, 5, 24], [12, 24, 3, 5], [12, 24, 5, 3], [12, 5, 3, 24], [12, 5, 24, 3], [5, 3, 24, 12], [5, 3, 12, 24], [5, 24, 3, 12], [5, 24, 12, 3], [5, 12, 3, 24], [5, 12, 24, 3]]
numbers_dict = dict(zip(name_list, num_list))
print(numbers_dict)

answer

{225.85: [12, 5, 24, 3], 286.818: [5, 24, 12, 3], 238.8: [24, 5, 12, 3], 282.43: [12, 24, 5, 3], 238.522: [24, 12, 5, 3], 238.378: [5, 12, 3, 24], 233.989: [12, 5, 3, 24], 294.957: [5, 3, 12, 24], 290.847: [12, 3, 5, 24], 282.286: [5, 24, 3, 12], 282.008: [5, 3, 24, 12], 229.961: [5, 12, 24, 3]}

My problem is the dictionary does not consist of all data that exists in the two lists above.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    hint: dicitonary keys are unique, withnew key and value, old value got override – sahasrara62 Jul 23 '23 at 20:50
  • 1
    Your list of keys has duplicates, a dictionary cannot have duplicate keys. What result did you expect? For example, this wouldn't work: `{225.85: [3, 24, 5, 12], 225.85: [12, 5, 24, 3]}` only the latter value survives the operation. @andrejkesely provided an answer that shows how to get the first instead of the last value, if that's what you wanted - but you can't have both/all. – Grismar Jul 23 '23 at 20:50

1 Answers1

2

Your name_list contains duplicate entries, so sequential keys are replaced. You can instead check for key presence and extend the list with additional values if key is present:

out = {}
for k, v in zip(name_list, num_list):
    out.setdefault(k, []).extend(v)

print(out)

Prints:

{
    225.85: [3, 24, 5, 12, 12, 5, 24, 3],
    286.818: [3, 12, 24, 5, 5, 24, 12, 3],
    238.8: [3, 12, 5, 24, 24, 5, 12, 3],
    282.43: [3, 5, 24, 12, 12, 24, 5, 3],
    238.522: [3, 5, 12, 24, 24, 12, 5, 3],
    238.378: [24, 3, 12, 5, 5, 12, 3, 24],
    233.989: [24, 3, 5, 12, 12, 5, 3, 24],
    294.957: [24, 12, 3, 5, 5, 3, 12, 24],
    290.847: [24, 5, 3, 12, 12, 3, 5, 24],
    282.286: [12, 3, 24, 5, 5, 24, 3, 12],
    282.008: [12, 24, 3, 5, 5, 3, 24, 12],
    229.961: [5, 12, 24, 3],
}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91