Simpler Way to Create Dictionary of Separate Variables

Simpler way to create dictionary of separate variables?

Are you trying to do this?

dict( (name,eval(name)) for name in ['some','list','of','vars'] )

Example

>>> some= 1
>>> list= 2
>>> of= 3
>>> vars= 4
>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
{'list': 2, 'some': 1, 'vars': 4, 'of': 3}

Divide a dictionary into variables

Problem is that dicts are unordered, so you can't use simple unpacking of d.values(). You could of course first sort the dict by key, then unpack the values:

# Note: in python 3, items() functions as iteritems() did
# in older versions of Python; use it instead
ds = sorted(d.iteritems())
name0, name1, name2..., namen = [v[1] for v in ds]

You could also, at least within an object, do something like:

for k, v in dict.iteritems():
setattr(self, k, v)

Additionally, as I mentioned in the comment above, if you can get all your logic that needs your unpacked dictionary as variables in to a function, you could do:

def func(**kwargs):
# Do stuff with labeled args

func(**d)

Convert dictionary entries into variables

This was what I was looking for:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')

Is there a way to create a dictionary by declaring variables that make up its key-value pairs?

You can simply use a list for this purpose

dblist = []
dblist.append( {"id": 1, "fn": "JM", "ln" : "Cruz", "dob": "October 5, 1980"})
dblist.append( {"id": 2, "fn": "JD", "ln" : "Castillo", "dob": "August 18, 1979"})
dblist.append({"id": 3, "fn": "Maria", "ln" : "Torres", "dob": "August 3, 1992"})
for db in dblist:
print("ID: " + str(db["id"]))
print("Full Name: " + db["fn"] + " " + db["ln"])
print("Birthday: " + db["dob"])
print("----------------------")

OUTPUT

ID: 1
Full Name: JM Cruz
Birthday: October 5, 1980
----------------------
ID: 2
Full Name: JD Castillo
Birthday: August 18, 1979
----------------------
ID: 3
Full Name: Maria Torres
Birthday: August 3, 1992
----------------------

Use for loop to create newly named variables from the keys of a dictionary

You can use the exec command, like this:

dict={}
for i in range (10):
key=str("x"+str(i))
dict[key]=i
for key,value in dict.items():
exec(f'{key}={value}')

Try adjusting this to your data.

A simpler way to create a dictionary with counts from a 43 million row text file?

Creating the zip_dict can be replaced with a defaultdict. If you can run through every line in the file, you don't need to do it twice, you can just keep a running count.

from collections import defaultdict

d = defaultdict(int)

with open(filename) as f:
for line in f:
parts = line.split('|')
d[parts[8]] += 1

How to store a dictionary as a separate file, and read the file in a python script to use the variables

You can replace this line:
gene_data = open("gene_data1.txt", "r")

with this:

import ast

with open('dict.txt') as f:
gene_data = f.read()
gene_data = ast.literal_eval(gene_data)

but make sure the text file just contains the dictionary, not the assignment of the dictionary:

{ 'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}

As pointed out by others, allowing your script to execute any command in a file can be dangerous. With this method, at least it won't execute anything in the external file, if the contents don't evaluate nicely the script will just throw an error.

Create dictionary where keys are variable names

Have you considered creating a class? A class can be viewed as a wrapper for a dictionary.

# Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)

# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()

# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c

# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}

Or you could use the setattr function if you wanted to pass a list of variable names:

mydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars:
setattr(mydict, v, eval(v))

mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}

How to assign the values of the nested dictionary to separate variables in python?

You just have to access the 'lo' and 'hi' keys and assign the values to the variables. Then you can calculate the ratio.

for ticker in df_dict:
lo, hi = df_dict[ticker]['lo'], df_dict[ticker]['hi']
print('Ratio:', lo / hi)


Related Topics



Leave a reply



Submit