Convert dictionary dictionaries into class

0

I have a dictionary that contains activities name and some characteristics of this activity.

I created a class called process and want to iterate in my dictionary creating processes.

process_name = ['processo1', 'processo2', 'processo3']
process_data = {
    'processo1': {
        'prod': 1.2,
        'maquinario': 'maq1'
    },
    'processo2': {
        'prod': 0.7,
        'maquinario': 'maq2'
    },
    'processo3': {
        'prod': 0.9,
        'maquinario': 'maq3'
    }
}

# ______________________________

class Process(object):
    def __init__(self , dictionary):
        for key in dictionary:
            setattr(self, key, dictionary[key])
# ______________________________

for name in process_name:
    processo = Process(process_data[name])
    name = processo

It is creating the object with the name name or process, not the name of the respective process.

How can I resolve this? Thank you!

    
asked by anonymous 12.09.2018 / 21:40

1 answer

0

Problem is within for in assignment to nome

for name in process_name:
    processo = Process(process_data[name])
    name = processo  # <------

The variable name is assigned correctly (although it does not have the effect you want) but is overwritten in the next iteration of the loop.

In order for you to access Process by name just replace:

    name = processo

By:

    process_data[name] = processo

So the changes will be modified in the original dictionary.

Below is an example of your modified code:

process_name = ['processo1', 'processo2', 'processo3']
process_data = {
    'processo1': {
        'prod': 1.2,
        'maquinario': 'maq1'
    },
    'processo2': {
        'prod': 0.7,
        'maquinario': 'maq2'
    },
    'processo3': {
        'prod': 0.9,
        'maquinario': 'maq3'
    }
}

# ______________________________
class Process(object):
    def __init__(self , dictionary):
        for key in dictionary:
            setattr(self, key, dictionary[key])

# ______________________________

for name in process_name:
    processo = Process(process_data[name])
    # única alteração no código
    process_data[name] = processo

# Dicionário atualizado com objetos do tipo Process
print(process_data)

# Acesso aos Process por nome
print(process_data['processo1'])

Code working

    
12.09.2018 / 23:04