List Element Configuration - python

So I have a list where each element is associated with a variable(s). If the user wants to read a variable value I would need to take an element of the list perform my operation and then return it to the user. The list is ~250 elements, where each element is defined as a different variable. The element number and variable do not change.
Do I need some form of lookup table, or equivalent? Does it go in the main code, or can I keep it separate as a config file, i.e. txt file containing: element 1 = variable y
I'm fairly new to Python, so just want to pointed in the right direction really.

The data structure you seem to be wanting is a dictionary. Dictionaries allow you to reference elements by their key i.e. a key could be a "variable" and the value associated with the key is essentially data that can be referenced by the "variable". Dictionaries can be made by defining a variable as {} or by using the dict() function on something. I most often will do something like:
dictionary = dict(zip(list_of_names , list_of_data))
The lists could be made by reading your txt file and then using:
string.split("your delimiter here")

Related

How do i access the sub details in the JSON using python?

the python program that i am writing calls to an api that returns this json:
Code Output
How do i access the subdetails? When i run the .keys() it only lists those three top levels. I want to be able to get specific items, e.g. "Utility"
I've tried several solutions but none parse correctly. I have tried calling the list inside the dictionary, to no avail. Originally i thought it was a dictionary inside of a dictionary, but Python thinks its a list nested into a dictionary.
Any help would be appreciated!
keys() function only returns the keys of dictionary, so it you call keys(), it will only return the three result. The "subdetails" you are referring to are the values of those keys. For key "SUMMARY" as an example, its value is a list instead of dict (note the "[" after the key). However, the list only has a single element. This is quite common in json. To retrive "Utility", all you need to do is data['SUMMARY'][0]['Utility']
Maybe to help you understand the data structure better, call the "values()" and "items()" function to see what it returns.
Since it's a dict of lists of dicts, simply use an index of 0 to access the first item of the list if there is always only one item in each list. For example, if your JSON object is stored as variable data, then the value of Utility can be accessed with data['SUMMARY'][0]['Utility'].

Appending to list within key value list in compact Python dictionary

I am looking to assess if there is a better method to append to a list within a list within a dictionary.
I have many different packets and associated strings to search for in a huge text file. Associated to each string is a value I want to store in a list so that I can perform calculations like average/max/min.
Due to the packet variations and associated strings for each packet I was looking to keep a dictionary entry to a single line. So I would have a Key as the packet ID and the value as a list of elements, see below
mycompactdict={
"packetID_001":[12,15,'ID MATCH',[['search_string',[] ],['search_string2',[] ]]]
"packetID_002":[...etc]
}
The 12,15 ints are references I use later in Excel plotting. The 'ID_MATCH' entry is my first check to see if the packet ID matches the file object. The 'search_string' references are the strings I am looking for and the blank lists next to them is where I hope to drop the values associated to each search string after splitting the line in the text file.
Now I may be biting off more than Python can chew... I realize there is a list within a list within a list within a list within a dict!
Here's a start of my code...
def process_data(file_object):
split_data = file_object.split('\n')
for key in mycompactdict:
if mycompactdict[key][2] in file_object:
for line in split_data:
if item[0] for item in mycompactdict[key][3] in line:
value = line.split('=', 1)
value.strip()
print value
and then append the stripped value to mycompactdict[key][6]item[1]
Am I on the wrong approach which will cause performance problems later on, and is there a cleaner alternative?
Below is an example of the file_object in the for of a unicode block of text, there are both matching and differing packet IDs I need to account for.
14:27:42.0 ID_21 <<(ID_MATCH)
Type = 4
Fr = 2
search_string1 = -12
search_string2 = 1242
I would not try to re-invent the wheel were I in your position. Thus, I would use Pandas. It has something called DataFrames that would be a good fit for what you are trying to do. In addition, you can export those into exel spread sheets. Have a look at the 10min introduction.

Create a dictionary with name of variable

I am trying to write a program to parse a file, break it into sections, and read it into a nested dictionary. I want the output to be something like this:
output = {'section1':{'nested_section1':{'value1':'value2'}}}
I'm trying to do this by building separate dictionaries, than merging them, but I'm running into trouble naming them. I want the dictionaries inside of the others to be named based on the sections of the file they're taken from. But it seems I can't name a dictionary from a variable.
You can name a dictionary entry from a variable. If you have
text = "myKey" # or myNumber or any hashable type
data = dict()
You can do
data[text] = anyValue
Store all your dictionaries in a single root dictionary.
all_dicts['output'] = {'section1':{'nested_section1':{'value1':'value2'}}}
As you merge dictionaries, remove the children from all_dicts.
all_dicts['someotherdict']['key'] = all_dicts['output']
del all_dicts['output']

Python: My dictionary that stores first names won't store more than one first name at a time

So, I've created a Dictionary that stores first-names as a list within that dictionary. New names are added within the dictionary's list via a function. Now, this is where i have hit a snag:
Main Obstacle: The function overwrites new names that I add. If I add the name "George" to the list via the function, it will store the name "George". But, I want to add the name "Alfred" within the dictionary, it overwrites the name "George" and adds the name "Alfred".
I am sure you can see how problematic this is for someone who wants to add multiple names to the dictionary's list. The odd thing is that when I type out the exact same code into the interpreter and I individually append names to the dictionary's list, it works fine.
Here is the code:
def add(data,value):
data['names'] = {}
data['names']['first'] = []
data['names']['first'].append(value)
Didn't you ask this question already? (My previous answer)
You are always setting the data['names'] to an empty dictionary before appending value to it.
def add(data, value):
data.setdefault('names', {}).setdefault('first', []).append(value)
See python docs on dict.setdefault

How to rewrite this Dictionary For Loop in Python?

I have a Dictionary of Classes where the classes hold attributes that are lists of strings.
I made this function to find out the max number of items are in one of those lists for a particular person.
def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable
max_vars=0
for key, value in patients[some_person].__dict__.items():
challenger=len(value)
if max_vars < challenger:
max_vars= challenger
return max_vars
What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like
for key in patients[some_person].__dict__:
value = patients[some_person].__dict__[key]
# then continue as before
I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it.
By the way, your existing function could be rewritten using a generator, like so:
def find_max_var_amt(some_person):
return max(len(value) for value in patients[some_person].__dict__.itervalues())
and if you did it that way, the change to iterating over keys would look like
def find_max_var_amt(some_person):
dct = patients[some_person].__dict__
return max(len(dct[key]) for key in dct)

Categories

Resources