-1

How to dynamically set the length of a Python dictionary (i.e. how to dynamically set the number of key values in a dictionary)

And each value (which will be an integer) of the dictionary should point to a list. This list should could be variable length for each key value of the dictionary.

Utpal Mattoo
  • 890
  • 3
  • 17
  • 41
  • Can you show your expected output? And what you've tried so far? – Cory Kramer May 08 '18 at 14:53
  • 4
    Python dictionaries are already dynamic. And what would it mean for an integer value to "point to" a list? – Daniel Roseman May 08 '18 at 14:54
  • 2
    I don't understand the question. If you want your dict to have a length of n, you add n elements to the dict. If you want more, you add more. If you want less, you remove some. – Aran-Fey May 08 '18 at 14:55

2 Answers2

1
  1. "How to dynamically set the length of a Python dictionary (i.e. how to dynamically set the number of key values in a dictionary)"

  2. "And each value (which will be an integer) of the dictionary should point to a list."

First of all, key values above in the first sentence are called simply keys in Python. Second, the things to which these keys "point" are called values. So, your lists are values.

To answer your first question: you can't set the length of the dictionary. Instead you simply add key-value pairs to the dictionary (or delete keys) and this is how you dynamically control the length of the dictionary.

What you really want, it seems to me (after some head scratching), is a defaultdict:

In [32]: from collections import defaultdict
    ...: d = defaultdict(list)
    ...: d['first'].append(1)
    ...: print(d['second']) # simply accessing a non-existant key
    ...:                    # creates the default value - an empty list
    ...: print(d)
    ...: 
[]
defaultdict(<class 'list'>, {'first': [1], 'second': []})
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
0

For the first part, you can initialize the dictionary with None. See here.

For the second part, dictionaries are already made up of key-value pairs, so if you want your dictionary's integer index to refer to a list, you could do this:

 # Initialize your dictionary
 new_dict = dict()

 # Add each list "manually"
 new_dict[0] = ['your', 'list', 'elements'] # 

 # Loop through the available lists and add them to your dictionary
 for i in range(100):
     new_dict[i] = list_of_lists[i]
natn2323
  • 1,983
  • 1
  • 13
  • 30