How to evaluate strings and use them as data names? - python

What I would like to do is evaluate strings and convert them in data types like,
If I have a string x = "helloW" and then read the value of x and make a list/function with the name helloW because the value of x is helloW. Suppose I have a file with many words and each line has a word and a number like:
lorem 1
ipsum 2
pac 3
heg 5
dis 7
Is there a way to make variables with name the words and value as numbers?
We can use a for loop and int(), but how do we name the variables?
Is there any way to do so in python?

You can use global() or a dictionary (code almost looks the same)
Creates variables
# directly create global vartiables
for every_line in input:
var_name, var_value = every_line.split()
globals()[var_name]=var_value
print(lorem, ipsum)
1 2
Creates a dictionary
my_variables = {} #empty dictionary
for every_line in input:
var_name, var_value = every_line.split()
my_variables[var_name]=var_value
print(my_variables)
{'lorem': '1', 'ipsum': '2', 'pac': '3', 'heg': '5', 'dis': '7'}
The pythonic way would be to use a dictionary!
globals() actually returns a dictionary representing the current global symbol table. That is why the code is so similar!

Instead of creating a new variable, you can store the variables in a dictionary.
vars = {}
for line in input:
name, value = line.split(' ')
vars[name] = int(value)
Now the dictionary vars will look like this.
>>> vars
{'lorem': 1, 'ipsum': 2, 'pac': 3, 'heg': 5, 'dis': 7}

Related

Creating python dictionaries using for loop

I make a bunch of matrices that I want to store in python dictionaries and I always find myself typing the same thing for every state that I want to build, i.e.
Ne21_1st_state = {}
Ne21_2nd_state = {}
Ne21_3rd_state = {}
Ne21_4th_state = {}
Ne21_5th_state = {}
Ne21_6th_state = {}
...
Ne21_29th_state = {}
Ne21_30th_state = {}
Can somebody help me automate this using python for loops?
Thanks in advance!
I want something like this:
for i in range(3, 11):
states = f'Ar36_{i}th_state'
print(states)
where the output would be:
Ar36_3th_state
Ar36_4th_state
Ar36_5th_state
Ar36_6th_state
Ar36_7th_state
Ar36_8th_state
Ar36_9th_state
Ar36_10th_state
but instead of printing it it would create individual dictionaries named Ar36_3th_state, Ar36_4th_state, Ar36_5th_state, ...
can't we make a List of dictionaries
List of 30 (or any N) elements where each element is a dictionary with key = "Ar36_{i}th_state" and value = {whatever value you want}
You can create "name" of pseudo variable and use it as key in dictionary like:
my_dic = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
my_empty_dic = {}
solution = {}
for i in range(1, 31):
name = 'Ne21_'+str(i)+'st_state'
#solution[name] = my_dic
solution[name] = my_empty_dic
for pseudo_variable in solution:
print(pseudo_variable, solution[pseudo_variable])
print(solution['Ne21_16st_state'])
for pseudo_variable in solution:
if '_16st' in pseudo_variable:
print(pseudo_variable, solution[pseudo_variable])
One way I've done this is using list comprehension.
key = list(
str(input(f"Please enter a Key for value {x + 1}: "))
if x == 0
else str(input(f"\nPlease enter a Key for value {x + 1}: "))
for x in range(3))
value = list(str(input(f"\nPlease enter a Bool for value {x + 1}: "))
for x in range(3))
BoolValues = dict(zip(key, value))
I first create a list of keys followed by a list of the values to be stored in the keys. Then I just zip them together into a dictionary. The conditional statements in the first list are only for a slightly better user-experience with \n being added if it's passed the first input.
Actually now that I look back on the question it may be slightly different to what I was thinking, are you trying to create new dictionaries for every matrix? If that is the case, is it something similar to this?: How do you create different variable names while in a loop?

python how to iterate a variable which consists of multiple lists

I have a variable that consists of the list after list after list
my code:
>>> text = File(txt) #creates text object from text name
>>> names = text.name_parser() #invokes parser method to extract names from text object
My name_parser() stores names into a list self.names=[]
example:
>>> variable = my_method(txt)
output:
>>> variable
>>> [jacob, david], [jacob, hailey], [judy, david], ...
I want to make them into single list while retaining the duplicate values
desired output:
>>> [jacob, david, jacob, hailey, judy, david, ...]
(edited)
(edited)
Here's a very simple approach to this.
variable = [['a','b','c'], ['d','e','f'], ['g','h','i']]
fileNames = ['one.txt','two.txt','three.txt']
dict = {}
count = 0
for lset in variable:
for letters in lset:dict[letters] = fileNames[count]
count += 1
print(dict)
I hope this helps
#!/usr/bin/python3
#function to iterate through the list of dict
def fun(a):
for i in a:
for ls in i:
f = open(ls)
for x in f:
print(x)
variable ={ "a": "text.txt", "b": "text1.txt" , "c":"text2.txt" , "d": "text3.txt"}
myls = [variable["a"], variable["b"]], [variable["c"], variable["d"]]
fun(myls)
print("Execution Completed")
You can use itertools module that will allow to transform your list of lists into a flat list:
import itertools
foo = [v for v in itertools.chain.from_iterable(variable)]
After that you can iterate over the new variable however you like.
Well, if your variable is list of lists, then you can try something like this:
file_dict = {}
for idx, files in enumerate(variable):
# you can create some dictionary to bind indices to words
# or use any library for this, I believe there are few
file_name = f'{idx+1}.txt'
for file in files:
file_dict[file] = [file_name]

Python - Swap a value for a dictionary item

So basically, I have my dictionary, which looks like this:
{'my': 2, 'Phil.': 10, 'name': 3, 'Andy.': 5, 'Hello': 1, 'is': 4}
and a string that looks like this:
1 2 3 4 5 1 2 3 4 10
How can I make it so each number in the string is replaced by the word with the same number in the dictionary? So it would make the sentence:
Hello my name is Andy. Hello my name is Phil.
I have no idea how to approach this, so help is appreciated.
First make from your string a list.
list_name = string_name.split(' ')
Then switch the keys and the values from your dict (if using python 3.x use iter instead of iteritems)
my_dict = {y:x for x,y in my_dict.iteritems()}
Then you can iter tro your code
for numbers in list_name:
print(my_dict[int(numbers)])

How do I fix the error "unhashable type: 'list'" when trying to make a dictionary of lists?

I'm trying to make a dictionary of lists. The input I am using looks like this:
4
1: 25
2: 20 25 28
3: 27 32 37
4: 22
Where 4 is the amount of lines that will be outputted in that format. The first thing I did was remove the "#: " format and simply kept each line like so:
['25']
['20','25','28']
['27','32','37']
['22']
So finally the goal was to take those values and put them into a dictionary with their assigned value in the dictionary being the length of how many numbers they held.
So I wanted the dictionary to look like this:
['25'] : 1
['20','25','28'] : 3
['27','32','37'] : 3
['22'] : 1
However, when I tried to code the program, I got the error:
TypeError: unhashable type: 'list'
Here is my code:
def findPairs(people):
pairs = {}
for person in range(people):
data = raw_input()
#Remove the "#: " in each line and format numbers into ['1','2','3']
data = (data[len(str(person))+2:]).split()
options = len(data)
pairs.update({data:options})
print(pairs)
findPairs(input())
Does anyone know how I can fix this and create my dictionary?
Lists are mutable, and as such - can not be hashed (what happens if the list is changed after being used as a key)?
Use tuples which are immutable instead:
d = dict()
lst = [1,2,3]
d[tuple(lst)] = "some value"
print d[tuple(lst)] # prints "some value"
list is an unhashable type, you need to convert it into tuple before using it as a key in dictionary:
>>> lst = [['25'], ['20','25','28'], ['27','32','37'], ['22']]
>>> print dict((tuple(l), len(l)) for l in lst)
{('20', '25', '28'): 3, ('22',): 1, ('25',): 1, ('27', '32', '37'): 3}

Convert string into integer separated by space

how to extract the integers from the string(integers separated by space) and assign them to different variables.
eg.
Given string: "2 3 4 5"
assign: n=2, m=3, x=4, y=5
Something like (read comments):
>>> s = "2 3 4 5"
>>> s.split() # split string using spaces
['2', '3', '4', '5'] # it gives you list of number strings
>>> n, m, x, y = [int(i) for i in s.split()] # used `int()` for str --> int
>>> n # iterate over list and convert each number into int
2 # and use unpack to assign to variables
the number of values in your string might be variable. In this case you could assign the variables to a dictionnary as follows:
>>> s = "2 3 4 5"
>>> temp = [(count, int(value)) for count, value in enumerate(s.split(' '), 1)]
>>> vars = {}
>>> for count, value in temp:
... vars['var' + str(count)] = value
>>> vars
{'var4': 5, 'var1': 2, 'var3': 4, 'var2': 3}
>>> vars['var2']
3
If you really don't want a dictionnary, you could consider the following:
>>> temp = [(count, int(value)) for count, value in enumerate(s.split(' '), 1)]
>>> for count, value in temp:
... locals()['var{}'.format(count)] = value
>>> var2
3
locals()['var{}'.format(count)] = value will add a local variable named 'var{count}' and assign the value to it. locals()shows you the local variables and its values.
Remember: do this only if you really know what you are doing. Read please also the note on locals in the Python documentation: "The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter."

Categories