-1

I am trying to build a dictionary based on a larger input of text. From this input, I will create nested dictionaries which will need to be updated as the program runs. The structure ideally looks like this:

nodes = {}

node_name: {
  inc_name: inc_capacity,
  inc_name: inc_capacity,
  inc_name: inc_capacity,
}

Because of the nature of this input, I would like to use variables to dynamically create dictionary keys (or access them if they already exist). But I get KeyError if the key doesn't already exist. I assume I could do a try/except, but was wondering if there was a 'cleaner' way to do this in python. The next best solution I found is illustrated below:

test_dict = {}

inc_color = 'light blue'
inc_cap = 2

test_dict[f'{inc_color}'] = inc_cap
# test_dict returns >>> {'light blue': 2}
Safak Ozdek
  • 906
  • 11
  • 18
mah111
  • 146
  • 8
  • 3
    Without knowing the nature of your input it's hard to give advice, could you give a reduced example of your input? The method you have used is fine, it's possible you could use a dictionary comprehension if you have an appropriate iterator – Iain Shelvington Dec 31 '20 at 09:11
  • 1
    Show the code producing `KeyError` – tevemadar Dec 31 '20 at 09:11
  • can use dict.get() function and default to None if no element found – billz Dec 31 '20 at 09:12
  • 1
    also you may want to look into `defaultdict`, https://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work – piterbarg Dec 31 '20 at 09:13
  • you can also use [defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict) – Nullman Dec 31 '20 at 09:13
  • 2
    The `dict` class already has the methods `dict.get(key, default)` and `dict.setdefault(key, value)`, which seem to be what you're looking for here – Green Cloak Guy Dec 31 '20 at 09:25

2 Answers2

1

Try this code, for Large Scale input. For example file input

Lemme give you an example for what I am aiming for, and I think, this what you want.

File.txt

Person1: 115.5
Person2: 128.87
Person3: 827.43
Person4:'18.9

Numerical Validation Function

def is_number(a):
    try:
        float (a)
    except ValueError:
        return False
    else: 
        return True

Code for dictionary File.txt

adict = {}
with open("File.txt") as data:
    adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip(' \n')  for line in data.readlines() if is_number(line[line.index(':')+1: ].strip('\n')) == True}
    print(adict)

Output

{'Person1': '115.5', 'Person2': '128.87', 'Person3': '827.43'}

For more explanation, please follow this issue solution How to fix the errors in my code for making a dictionary from a file

Ahmed
  • 796
  • 1
  • 5
  • 16
0

As already mentioned in the comments sections, you can use setdefault.

Here's how I will implement it.

Assume I want to add values to dict : node_name and I have the keys and values in two lists. Keys are in inc_names and values are in inc_ccity. Then I will use the below code to load them. Note that inc_name2 key exists twice in the key list. So the second occurrence of it will be ignored from entry into the dictionary.

node_name = {}

inc_names = ['inc_name1','inc_name2','inc_name3','inc_name2']
inc_ccity  = ['inc_capacity1','inc_capacity2','inc_capacity3','inc_capacity4']

for i,names in enumerate(inc_names):
    node = node_name.setdefault(names, inc_ccity[i])
    if node != inc_ccity[i]:
        print ('Key=',names,'already exists with value',node, '. New value=', inc_ccity[i], 'skipped')

print ('\nThe final list of values in the dict node_name are :')
print (node_name)

The output of this will be:

Key= inc_name2 already exists with value inc_capacity2 . New value= inc_capacity4 skipped

The final list of values in the dict node_name are :
{'inc_name1': 'inc_capacity1', 'inc_name2': 'inc_capacity2', 'inc_name3': 'inc_capacity3'}

This way you can add values into a dictionary using variables.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33