Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable names with dictionaries?

Python beginner here. A question about dictionaries.

My input is a variable length list (eg a = ['eggs', 'ham', 'bacon'...] ) which functions as a list of search terms to be used on an imported CSV file.

I have defined four functions that match each term to various values from said CSV file. So, each input term will result in four lists of results.

I would like to store the input terms as a key in a dictionary (easy enough) and the resulting four lists as values (also easy enough).

However, because the input list is of variable length I would like to set up a function to define and name the dictionaries 'term1', 'term2', illustrated very basically thus:

term1 = { 'eggs' : [[list1] , [list2] , [list3] , [list4]] }
term2 = { 'ham' : [[list1] , [list2] , [list3] , [list4]] }
term3 = { 'bacon' : [[list1] , [list2] , [list3] , [list4]] }

Is there a) a way to name dictionaries like this?; and b) AND have them be globally available? If so, how? Any and all help very much appreciated.


1 Answers

Not an approach I'd recommend, but you can access both the local and global namespaces as dictionaries; e.g. you can add arbitrary variables to those namespaces using the familiar dict interface:

>>> globals()['foo'] = 'bar'
>>> foo
'bar'
>>> locals()['spam'] = 'eggs'
>>> spam
'eggs'

You will run into naming conflicts though. Also, how will the rest of your code know what global variables contain your results? They'll have to do indirect look-ups too!

You better just use one dictionary containing your results, and let that be the namespace instead of the global namespace.

like image 54
Martijn Pieters Avatar answered Jul 18 '26 19:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!