converting variable like string content to real variable in python - python

I have string variable which contains "variable" like content as shown below.
str1="type=gene; loc=scaffold_12875; ID=FBgn0207418; name=Dvir\GJ20278;MD5=4c62b751ec045ac93306ce7c08d254f9; length=2088; release=r1.2; species=Dvir;"
I need to make variables out of the string such that the variables name and values goes like this
type="gene"
loc="scaffold_12875"
ID="FBgn0207418"
name="Dvir\GJ20278"
MD5="4c62b751ec045ac93306ce7c08d254f9"
length=2088
release="r1.2"
species="Dvir"
Thanks for the help in advance.

Don't do this. You could, but don't.
Instead make a dictionary whose keys are the names:
result_dict = {}
items = str1.split(';')
for item in items:
key, value = item.strip().split('=')
result_dict[key] = value

Or you could do this
class Namespace(object):
pass
for item in str1.split(';'):
key, value = item.strip().split('=', 1)
setattr(Namespace, key, value)
You can then access your variables like so
Namespace.length

Related

Concatenate iterator to variable name

I'd like to call a variable with a number in the name. I think the closest I've come is concatenating an iterator onto the name, and casting that as a dictionary but it doesn't work.
This is what I have tried:
dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}
for i in range(3):
tempDict = "dict"+str(i) # type is string
print(dict(tempDict))
output: ValueError: dictionary update sequence element #0 has length 1; 2 is required
These dictionaries are being populated with a database call, and the tables are numbered 0,1,2...n. Some days I have one dictionary, and some days multiple. It would be really convenient to be able to call them and act on the contents iteratively if possible. I'm not sure what to google for an answer, thank you in advance.
Assuming you have created the variables with the correct names (in this case dict0, dict1, dict2) you can get the values via their name using the vars() method
dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}
for i in range(3):
print(vars()[f"dict{i}"])
This prints each dict as expected
if you want to access dictionaries by their variable name try this:
dict0 = {"pet1":"dog", "pet2":"cat", "pet0":"bird"}
dict1 = {"first":"a", "second":"b", "third":"c"}
dict2 = {"num1":1,"num2":2,"num3":3}
for i in range(3):
dict_var_name = "dict"+str(i) # type is string
print(globals()[dict_var_name])
globals() return a dictionary which caontain all defined variables in global scope. for more information on this look at this question

How to make multiple variables from one string

I have a string containing a few variables that I would like to store.
data = '{name:ItCameFr0mmars,id:2110939,score:2088205,level:43,l
evelProgress:35,kills:18412,deaths:6821,kdr:2.70,kpg:12.03,spk:
113.42,totalGamesPlayed:1530,wins:913,loses:617,wl:0.60,playTim
e:2d 15h 1m,funds:2265,clan:TyDE,featured:No,hacker:false,follo
wing:0,followers:3,shots:117902,hits:38132,nukes:6,meleeKills:3
77,createdDate:2019-03-13,createdTime:21:38:39,lastPlayedClass:
Triggerman}'
I want to assign a variable for each bit of data. For example:
level = 43
kills = 18412
and so on.
Is there a way to do this, as each example: number would become a variable with that number stored? Also? how could I make a dictionary for it?
Here is a basic parser:
for name, val in [item.split(':', maxsplit=1) for item in data.strip("{}").split(",")]:
globals()[name] = val
print(featured)
If you want to do this in a function. Just replace globals with locals.
Usually it is better to put it into an object:
class Data():
def __init__(self, data):
for name, val in [item.split(':', maxsplit=1) for item in data.strip("{}").split(",")]:
setattr(self, name, val)
obj = Data(data)
print(obj.featured)
Why don't you make it like a dictionary like this
data = {"name":"ItCameFr0mmars","id":2110939,"score":2088205}
So you can get each value based on its key.
data["id"] will be 2110939
And if you want to print all them, you could write
for key,value in data.items():
print(key,":",value)
But I guess this is not what you wanted to do?

How do i retrieve the variable name for each dict in a list of dicts?

I may be missing something fundamental here but consider the following:
graph=nx.read_graphml('path here...')
dDict=dict(nx.degree_centrality(graph)) #create dict
lDict=dict(nx.load_centrality(graph))
new_lists=[dDict,lDict]
for i in new_lists:
print().... #how to get variable name i.e. dDict
how do i iterate through the list of dicts so that when i do a print it returns me the variable name the dict equals i.e. i want to be able to retrieve back 'dDict' and 'lDict'?I do not want a quick hack such as
dDict['name'] = 'dDict'
Any ideas..?
EDIT: the reason i want to do this is so that i can append these centrality measures to a dataframe with new column name i.e.:
for idx in range(len(new_lists)):
for i in range(len(df)):
rowIndex = df.index[i]
df.loc[rowIndex, idx] = new_lists[idx][rowIndex] #instead of idx how do i dynamically name the column according to the list item name.
You can iterate over globals() and get the variable name of the object that matches the content you are looking for.
More info on https://docs.python.org/3/library/functions.html?highlight=globals#globals
However, this is a rather cumbersome trick, you should not do that! Rather, redesign your software so you don't have to look for the variable names in the first place.
def get_var_name_of(x):
return [k for k,v in globals().items() if v==x][0]
dDict = {1:'asd'}
lDict = {2:'qwe'}
new_list=[dDict,lDict]
for d in new_list:
print(get_var_name_of(d))
dDict
lDict

Python: Dynamically update a dictionary with varying variable "depth"

I have a dictionary with various variable types - from simple strings to other nested dictionaries several levels deep. I need to create a pointer to a specific key:value pair so it can be used in a function that would update the dictionary and could be called like so:
dict_update(my_dictionary, value, level1key, *level2key....)
Data coming from a web request like this:
data {
'edited-fields': ['level1key-level2key-level3key', 'level1key-level2key-listindex', 'level1key'],
'level1key-level2key-level3key': 'value1',
'level1key-level2key-listindex': 'value2',
'level1key': 'value3'
}
I can get to the original value to read it like this:
for field in data["edited-fields"]:
args = field.split("-")
value = my_dictionary
for arg in args:
if arg.isdigit():
arg = int(arg)
value = value[arg]
print(value)
But have no idea how to edit it using the same logic. I can't search and replace by the value itself as there can be duplicates and having several if statements for each possible arg count doesn't feel very pythonic.
EXAMPLE:
data {
'edited-fields': ['mail-signatures-work', 'mail-signatures-personal', 'mail-outofoffice', 'todo-pending-0'],
'mail-signatures-work': 'I'm Batman',
'mail-signatures-personal': 'Bruce, Wayne corp.',
'mail-outofoffice': 'false',
'todo-pending-0': 'Call Martha'
}
I'd like to process that request like this:
for field in data['edited-fields']:
update_batman_db(field, data[field])
def update_batman_db(key-to-parse, value):
# how-to?
# key-to-parse ('mail-signatures-work') -> batman_db pointer ["mail"]["signatures"]["work"]
# etc:
batman_db["mail"]["signatures"]["work"] = value
batman_db["mail"]["outofoffice"] = value # one less level
batman_db["todo"]["pending"][0] = value # list index
The hard part here is to know whether an index must be used as a string form a mapping of as an integer for a list.
I will first try to process it as an integer index on a list, and revert to a string index of a mapping in case of any exception:
def update_batman_db(key, value):
keys = key.split('-') # parse the received key
ix = batman_db # initialize a "pointer" to the top most item
for key in keys[:-1]: # process up to the last key item
try: # descending in the structure
i = int(key)
ix = ix[i]
except:
ix = ix[key]
try: # assign the value with last key item
i = int(keys[-1])
ix[i] = value
except:
ix[keys[-1]] = value

Dynamic Python Lists

In the below Python Code, am dynamically create Lists.
g['quest_{0}'.format(random(x))] = []
where random(x) is a random number, how to print the List(get the name of the dynamically created List name?)
To get a list of all the keys of your dictionary :
list(g.keys())
There is nothing different with a regular dictionary because you generate the key dynamically.
Note that you can also put any type of hashable object as a key, such as a tuple :
g[('quest', random(x))] = []
Which will let you get a list of all your quest numbers easily :
[number for tag, number in g.keys() if tag == "quest"]
With this technic, you can actually loop through the tag ('quest'), the number and the value in one loop :
for (tag, number), value in g.items():
# do somthing
Unpacking is your best friend in Python.
You can iterate over the g dictionary with a for loop, like this
for key, value in g.items():
print key, value
This will print all the keys and their corresponding lists.

Categories

Resources