Home python Adding a list elements in the Python dictionary

Adding a list elements in the Python dictionary




Good day to all. I am trying to add the list items to the dictionary on a specific feature. The task is to sort the array. The number of dictionary keys is the number of discharges in numbers that are not repeated. When you try to sort items in the dictionary, the entire list is added, and at the same time on all keys. How to fix it?

def radix_sort (arr, n):
  Digits = Digits (Arr, N)
  a = {} .FromKeys (Digits, [])
  for el in arr:
    A [INT ((El% Pow (10, N)) / POW (10, N-1))]. Append (EL)
  Print (A [2])
  Return Arr.
  Digits = []
  For Num In Arr:
    Digit = int ((Num% Pow (10, N)) / POW (10, N-1)) #Int (STR (NUM) [LEN (STR (NUM)) - N]
    IF Not Digit in Digits:
      Digits.APPEND (Digit)
  Return Digits.
DEF Main ():
  a = []
  Size = int (Input ("Enter the size of the array:"))
  Print ("Enter the elements of the array:")
  For i in Range (Size):
  A = RADIX_SORT (A, 1)
Main ()

Answer 1, Authority 100%

Problem in this line:

a = {} .fromkeys (Digits, []
            ^^ & lt; - one list as a value for all dictionary keys

Each dictionary key will specify the same empty list and adding items to the list according to any of the dictionary keys will simultaneously replenish all lists of this dictionary. In English SO disassemble this case and offer, for example, to use vocabulary Instead of fromkeys . In your case it will look like this:

a = {k: [] for k in digits}
    ^^ & LT; - Different lists for different dictionary keys

Each time you see the design [] Python creates a new empty list. In the dictionary turn on, this design is called in the cycle, so different lists are obtained.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions