Home > Mobile >  Does anybody know how to add 1 to the naming of these nested dictionaries?
Does anybody know how to add 1 to the naming of these nested dictionaries?

Time:12-06

The following example below creates a dictionary named special from a list named example, those dictionary values are nested in a form similar to

{'name0' :
 {'name' : 'Harry James Potter',
 'phone' : 'n/a',
 'address' : '4 Pivet Drive Little Whinging, Surrey'}} 

and next would be for an example

 {'name1' :
 {'name' : 'Sirius Black',
 'phone' : 'n/a',
 'address' : '12 Grimald Place London'}}

what I am wondering and not able to accomplish is how to change the last line of code below to name the nested dictionaries beginning from 'name1' and so on and so forth...

example=[]
with open(sys.argv[1], encoding='utf-8-sig', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        return_from_add_2.append(row)
special = {f'name{i}':v for i, v in enumerate(example)}

I've tried to add an i=1 to the last line inside of and right before it but i get a syntax error.

CodePudding user response:

You have two options.

Option 1: tell enumerate to start with 1

special = {f'name{i}':v for i, v in enumerate(example, 1)}

Option 2: increment i by 1 inside the f-string

special = {f'name{i 1}':v for i, v in enumerate(example)}

Example:

example = [("v1", "v2"), ("v3", "v4")]
special1 = {f'name{i}':v for i, v in enumerate(example, 1)}
special2 = {f'name{i 1}':v for i, v in enumerate(example)}

Output:

{'name1': ('v1', 'v2'), 'name2': ('v3', 'v4')}
{'name1': ('v1', 'v2'), 'name2': ('v3', 'v4')}

CodePudding user response:

The inner data structure is a nested dictionary and it seems they key name is unique for each entry you want to reference. Below are a couple of methods to access the data.

You can dynamically generate the key and use that to access the value.

list_of_nested_dictionaries = [{'name0' : {'name' : 'Harry James Potter', 'phone' : 'n/a', 'address' : '4 Pivet Drive Little Whinging, Surrey'}},{'name1' : {'name' : 'Sirius Black', 'phone' : 'n/a', 'address' : '12 Grimald Place London'}}]
i = 0
for nested_dictionary in list_of_nested_dictionaries:
    dynamic_key = f'name{i}'
    character_name = nested_dictionary.get(dynamic_key).get('name')
    print(f'{character_name}')
    i =1

You can use the dictionary in-built functions to access the data

list_of_nested_dictionaries = [{'name0' : {'name' : 'Harry James Potter', 'phone' : 'n/a', 'address' : '4 Pivet Drive Little Whinging, Surrey'}},{'name1' : {'name' : 'Sirius Black', 'phone' : 'n/a', 'address' : '12 Grimald Place London'}}]
for nested_dictionary in list_of_nested_dictionaries:
    for key in nested_dictionary.keys():
        character_name = nested_dictionary.get(key).get('name')
        print(f'{character_name}')
  • Related