开发者

Need to assign value to a dictionary, whose name is stored in a variable (Python)

I have 2 questions pertaining to following code:

data = csv.DictReader(open('dc_sample.csv'), delimiter=',')

device_names = ['dev1', 'dev2', 'dev3'] # 
for row in data:
       for word in device_names:     # 
              name = word + '_data'  # To create dictionaries with variable names (eg.     dev1_data)
              vars()[name] = {}      #

              if word == row['Device']:
                      vars()[name] = vars()[name].update(row)   ### 
                      ################ OR #################
                      word + 'data' = word + 'data'.update(row) ##

1) "data" is a object created by a csv module, which reads from csv-file. "data" is in the form of dictionary, but with multiple rows. I want to create similar multiple dictionaries, which contains other keys & values of "data" for the same device_name. i.e. for Device = dev1, a dictionary with all the other key:values is created (which is named dev1_data).

2) Also please let me know, how can I modify a dictionary/list, whose variable_name is stored in another variable. for eg. name = word + 'data'

Please let me know, where my understanding is incorrect开发者_如何学运维 and how can I rectify the code.

Awaiting your reply.. Thank you in advance


Things like word + 'data' = ... do not work. You don't need to do that at all. Why would you want "to create dictionaries with variable names"? You should simply use a dictionary:

output = {}
for row in data:
   for word in device_names: 
        name = word + '_data'  # To create dictionaries with variable names (eg.     dev1_data)
        output[name] = {}
        if word == row['Device']:
            output[name] = output[name].update(row)   ### 

but it seem that this code won't work as it's doing output[name] = {} way too often.

Maybe you intended something like

output = {dev_name+ '_data' : {} for dev_name in device_names}

for row in data:
    dev_name = row['Device']
    if dev_name in device_names:
        output[dev_name+ '_data'].update(row)


I would use nested dicts rather than a bunch of dicts of various names, but example for question 2:

adict = {'a': 1, 'b':2}
whichdict = 'adict'
eval(whichdict)['b'] = 3
print(adict) #{'a': 1, 'b': 3}

For question 1:

newname = 'foo_data'
exec(newname + '= {}')
print(foo_data) #empty dict

See docs on eval and exec. Using globals and locals (documented same page as eval) may be slightly less abusive. I wouldn't consider any of these approaches to be particularly pythonic, though: nested dicts are probably better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜