Python Forum
Create X Number of Variables and Assign Data
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create X Number of Variables and Assign Data
#1
Good morning,

I'm trying to create a number of variables that is dynamic.

Lets say I have a string

sentence = "All work and no play makes Jack a dull boy."

and I count the number of words in the string using a counting scheme of some sort and arrive at a value of 10.

I then want to create 10 variables and store each separate word into a different variable.

I think I could use a function like this:

while i < num_vars:
var_name = ??? - I think I could just loop through numbers and concatenate for a name. Ie.. "var_" concatenated with i , then iterate i
var_value = ??? - Should I use some string split function in python, or assign to an array and use array functions?
exec(var_name + " = " + var_value)

Thanks again for the help and I hope this makes sense.
Reply
#2
Don't try to dynamically create variables, because that will lead to code that's difficult to maintain. Instead, use a list if you want to keep items in order, or use a dictionary if you want to associate names with the values.
RockBlok, snippsat, buran like this post
Reply
#3
I'm just working through one of the tutorial exercises, not sure if it ever makes sense to store in variables for later reuse (days or weeks later), but I'm fairly new at this.

This code seems to do what I was looking for though.

sentence = "All work and no play makes Jack a dull boy."

print("The original sentence is: '", sentence, "'")

print("")

string_length = len(sentence)
print("length of string is: ", string_length)
         
delimeter = " "

string_array = [string_length]
string_array = sentence

#if empty string set modifier to 0
if string_length == 0:
    count_modifier = 0
else:
    count_modifier = 1

num_vars = string_array.count(delimeter,0)+count_modifier

print("The number of words in the sentence is: ", num_vars)

i = 0

var_assignment_string = ""

#Builds a string for assigning variable data from a list
while i < num_vars:

    var_name = "var_" + str(i)
    var_assignment_string = var_assignment_string + var_name + ","
    i = i + 1

var_exec_string = var_assignment_string + " = sentence.split(' ')"

exec(var_exec_string)


print(var_0)
print(var_5)
print(var_9)
Reply
#4
Please, don't do this. Use proper data structure like list or dict.
By the way, there are plenty of odd things in this code you show
By the way, you can use indexes directly on the string, no need of lists, or dynamically created variables
sentence = "All work and no play makes Jack a dull boy."
delimiter = ' '

words = sentence.split(delimiter)
print(f'First word is: {words[0]}')
print(f'Sixth word is: {words[5]}')
Output:
First word is: All Sixth word is: makes
RockBlok likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Hopefully I get better at this haha.

I think the next chapter in the book gets into that, I'll try to avoid being odd in the future LOL
Reply
#6
More like this.
sentence = "All work and no play makes Jack a dull boy."
print(f"The original sentence is: '{sentence}'\n")

string_length = len(sentence)
print(f"Length of string is: {string_length}")
words = sentence.split()
word_dict = {f"var_{i}": word for i, word in enumerate(words)}
num_words = len(words)
print(f"The number of words in the sentence is: {num_words}")
# Use word_dict 
print(word_dict["var_0"])
print(word_dict["var_5"])
if "var_10" in word_dict:
    print(word_dict["var_10"])
else:
    print("The sentence does not have a eleventh word.")
Output:
Length of string is: 43 The number of words in the sentence is: 10 All makes The sentence does not have a eleventh word.
So as suggests before in post,i make dictionary and do not mess with dynamically variables hidden in globals() dictionary.
>>> word_dict
{'var_0': 'All',
 'var_1': 'work',
 'var_2': 'and',
 'var_3': 'no',
 'var_4': 'play',
 'var_5': 'makes',
 'var_6': 'Jack',
 'var_7': 'a',
 'var_8': 'dull',
 'var_9': 'boy.'}

>>> word_dict['var_3']
'no'
>>> word_dict.get('var_8')
'dull'
>>> word_dict.get('var_11', 'Value not in word_dict')
'Value not in word_dict'
RockBlok likes this post
Reply
#7
Maybe this is the step in the lesson plan where you learn that having dynamic variables is required for some tasks. In lesson 2 you learn that Python already has a dynamic variable that does exactly what you want, and it is called a list.
RockBlok and ndc85430 like this post
Reply
#8
What happens if a word repeats? What about punctuation? Lose the punctuation?

I think there are already modules for doing this kind of thing.

from collections import Counter
sentence = "All work and no play makes Jack a dull boy. Jack is a dull boy. Work makes him dull."
words = sentence.split()
wordCount = Counter(words)
Output:
Counter({'Jack': 2, 'a': 2, 'dull': 2, 'boy.': 2, 'All': 1, 'work': 1, 'and': 1, 'no': 1, 'play': 1, 'makes': 1, 'is': 1})
type(wordCount)
Output:
<class 'collections.Counter'>
wordCount['Jack']
Output:
2
Reply
#9
I concur that dictionary or list is the way to go.

One way to create dictionary from sentence can be dictionary comprehension:

>>> sentence = "All work and no play makes Jack a dull boy."
>>> {f"var_{i}": v for i, v in enumerate(sentence.split())}
{'var_0': 'All', 'var_1': 'work', 'var_2': 'and', 'var_3': 'no', 'var_4': 'play', 'var_5': 'makes', 'var_6': 'Jack', 'var_7': 'a', 'var_8': 'dull', 'var_9': 'boy.'}
>>>
RockBlok likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Better python library to create ER Diagram by using pandas data frames as tables klllmmm 0 1,151 Oct-19-2023, 01:01 PM
Last Post: klllmmm
Question How create programmatically variables ? SpongeB0B 6 1,339 Aug-19-2023, 05:10 AM
Last Post: SpongeB0B
  Delete strings from a list to create a new only number list Dvdscot 8 1,557 May-01-2023, 09:06 PM
Last Post: deanhystad
  Create simple live plot of stock data dram 2 2,938 Jan-27-2023, 04:34 AM
Last Post: CucumberNox
  Create a function for writing to SQL data to csv mg24 4 1,179 Oct-01-2022, 04:30 AM
Last Post: mg24
  Best way to accommodate unknown number of variables? Mark17 9 3,757 May-30-2022, 03:57 AM
Last Post: Skaperen
  Create array of values from 2 variables paulo79 1 1,106 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  How to create 2 dimensional variables in Python? plumberpy 5 1,877 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  Strategy on updating edits back to data table and object variables hammer 0 1,208 Dec-11-2021, 02:58 PM
Last Post: hammer
  How can I assign "multiple variables" to a single "value"? Psycpus 2 1,873 Oct-04-2021, 03:29 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020