I have a dictionary containing variables and their values.
This is my dictionary, for example:
{27: 'choice = input("Enter choice(1/2/3/4): ")',
31: 'num1 = float(input("Enter first number: "))',
32: 'num2 = float(input("Enter second number: "))',
48: 'next_calculation = input("Let\'s do next calculation? (yes/no): ")'}
and I want to go over values in the dictionary and save a substring of the string in the list.
The output should look like this from the previous dict:
list = ['choice','num1','num2','next_calculation']
How can I do this?
Use a list comprehension. Assuming d the input dictionary.
lst = [x.split()[0] for x in d.values()]
output: ['choice', 'num1', 'num2', 'next_calculation']
NB. do not name your variable list, this is a python builtin
If you have a very long string or want to explicitly define a different separator, use:
lst = [x.split(sep=' = ', maxsplit=1)[0] for x in d.values()]
Related
I am writing a program that can take in three numbers and three letters on seperate lines. The program will then seperate the numbers into items of a list and will do the same for the letters in a separate list. The program will then sort the the numbers from lowest to highest. I then want to assign the numbers to letters (In a sorted letter order (I.E. A=5, B=16, C=20) and then print the letters in the order it came in from the input (I.E. Input: CAB, output: 20 5 16). I have been able to sort the variables and can do all of this with if statements and for loops but I feel like there is a prettier and more efficient way of doing this. I want to be able to take the input letter string that's divided by use of a list and format the string to insert the variables in the correct order. I know that the globals() and locals() functions do something similar to this but can not figure out how to use them. Any ideas?
Working code:
nput_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
print_string = ""
for i in range(3):
if input_letters[i] == "A":
print_string = print_string + A + " "
if input_letters[i] == "B":
print_string = print_string + B + " "
if input_letters[i] == "C":
print_string = print_string + C + " "
print(print_string)
My (wanted) code:
input_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
A = str(input_numbers_list[0])
B = str(input_numbers_list[1])
C = str(input_numbers_list[2])
final_list = ["""Magic that turns input_letters_list into variables in the order used by list and then uses that order"""]
print("{} {} {}".format("""Magic that turns final_list into variables in the order used by list and then puts it in string""")
Wanted/expected input and output:
Input: "5 20 16"
Input: "CAB"
Output: "20 5 16"
As others have suggested, you will likely want an answer that uses a dictionary to lookup numbers given letters.
##----------------------
## hardcode your input() for testing
##----------------------
#input_numbers = input()
#input_letters = input()
input_numbers = "5 20 16"
input_letters = "CAB"
input_numbers_list = input_numbers.split(" ")
input_letters_list = list(input_letters) # not technically needed
##----------------------
##----------------------
## A dictionary comprehension
# used to construct a lookup of character to number
##----------------------
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
##----------------------
##----------------------
## use our original letter order and the lookup to produce numbers
##----------------------
result = " ".join(lookup[a] for a in input_letters_list)
##----------------------
print(result)
This will give you your requested output of:
20 5 16
There is a lot going on with the construction of the dictionary lookup, so let's unpack it a bit.
First of, it is based on calling zip(). This function takes two "lists" and pairs their elements up creating a new "list". I use "list" in quotes as it is more like iterables and generators. Anyways. let's take a closer look at:
list(zip(["a","b","c"], ["x","y","z"]))
this is going to give us:
[
('a', 'x'),
('b', 'y'),
('c', 'z')
]
So this is how we are going to pairwise combine our numbers and letters together.
But before we do that, it is important to make sure that we are going to pair up the "largest" letters with the "largest" numbers. To ensure that we will get a sorted version of our two lists:
list(
zip(
sorted(input_letters_list), #ordered by alphabet
sorted(input_numbers_list, key=int) #ordered numerically
)
)
gives us:
[
('A', '5'),
('B', '16'),
('C', '20')
]
Now we can feed that into our dictionary comprehension (https://docs.python.org/3/tutorial/datastructures.html).
This will construct a dictionary with keys of our letters in the above zip() and values of our numbers.
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
print(lookup)
Will give us our lookup dictionary:
{
'A': '5',
'B': '16',
'C': '20'
}
Note that our zip() technically gives us back a list of tuples and we could also use dict() to cast them to our lookup.
lookup = dict(zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
))
print(lookup)
also gives us:
{
'A': '5',
'B': '16',
'C': '20'
}
But I'm not convinced that clarifies what is going on or not. It is the same result though so if you feel that is clearer go for it.
Now all we need to do is go back to our original input and take the letters one by one and feed them into our lookup to get back numbers.
Hope that helps.
Its very weird the case when you need to conver string to a variable, when you feel that you need something like that a dictionary will probably do the trick.
in this case the solution can be done with the following code.
input_numbers_list = (("5 20 16").split(" "))
input_letters = ("CAB")
input_letters_list = [letter for letter in input_letters]
input_numbers_list = [int(x) for x in input_numbers_list]
rules = {}
for letter, value in zip(input_letters_list, input_numbers_list):
rules[value] = letter
output = ""
input_numbers_list.sort()
for numb in input_numbers_list:
output += rules[numb] + " "
print(output)
And you can use it for n inputs and outputs.
The idea of a dictionary is that you have keys, and values, so for a key (in this case text of letters) you can get a value, similar to a variable. Plus is super fast.
You could use a dictionary for that! https://www.w3schools.com/python/python_dictionaries.asp
EDIT: the output is more consistent with the requested one, but it should be "20 16 5" instead of "20 5 16" if I understood your problem well.
input_numbers_list = input().split(" ")
input_letters = input()
# Create new dictionary
input_dict = {}
# Fill it by "merging" both lists
for index, letter in enumerate(input_letters):
input_dict[letter] = input_numbers_list[index]
# Sort it by converting it into a list and riconverting to dict
sorted_dict = {k: v for k, v in sorted(list(input_dict.items()))}
# Print the result
output = ''
for value in sorted_dict.values():
output += value + ' '
print(output)
Using zip function helps
num_arr = list(map(int,input().split(' ')))
word = input()
num_arr.sort()
word = sorted(word)
mapper = dict(zip(word,num_arr))
result = ' '.join(map(str,[mapper[i] for i in word]))
print(result)
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?
these are the inputs:
name:SignalsAndSystems genre:engineering author:Oppenheim
name:calculus genre:mathematics author:Thomas
name:DigitalSignalProcessing genre:engineering author:Oppenheim
and I tried to make dictionaries of each line separated by ":" for example name:SignalsAndSystems.
this is my code but the code makes dictionaries only from the first line of the inputs.
lst_inps = []
for i in range(2):
inp = input()
inp = inp.split(" ")
for item in inp:
attribute, value = item.split(":")
dict.update({attribute: value})
lst_inps.append(dict)
the answer that I'm looking for is:
[
{"name":"SignalsAndSystems", "genre":"engineering", "author":"Oppenheim"} ,
{"name":"calculus", "genre":"mathematics", "author":"Thomas"} ,
{"name":"DigitalSignalProcessing", "genre":"engineering", "author":"Oppenheim"}
]
You aren't creating a dictionary in your for loop. You need to create a dictionary, then update it with your new key value pairs, before appending it to your list.
lst_inps = []
for i in range(3):
new_dict = dict() # create the dictionary here
inp = input()
inp = inp.split(" ")
for item in inp:
attribute, value = item.split(":")
new_dict.update({attribute: value}) # add your key value pairs to the dictionary
lst_inps.append(new_dict) # append your new dictionary to the list
print(lst_inps)
I have a list of sentence and I want to convert it into a diction only include the username and the age.
list=['#David, the age is 27', '#John, the age is 99', '#rain, the age is 45']
The output I want to get is a dictionary like
dic={David:27,John:99,rain:45}
Thanks for the help
You can define a custom function, apply it to each string via map, then feed to dict:
L = ['#David, the age is 27', '#John, the age is 99', '#rain, the age is 45']
def key_value_extractor(x):
x_split = x.split(',') # split by ','
name = x_split[0][1:] # take 1st split and exclude first character
age = int(x_split[1].rsplit(maxsplit=1)[-1]) # take 2nd, right-split, convert to int
return name, age
res = dict(map(key_value_extractor, L))
{'David': 27, 'John': 99, 'rain': 45}
Try a dict comprehension:
dic = {x.split()[0].strip(',#'): int(x.split()[-1]) for x in member_list}
If you need clarification on the parts of the expression, please tell.
EDIT: Clarification, as required:
Ok, so:
enclosing the expression in {} tells it we are making a dictionary with this comprehension. x represents each member string within this comprehension
x.split() splits the string into a list of substrings, on "space" sign (by default, can be adjusted)
with [0] we grab the first substring ["#David,"]
with .strip(',#') we remove the comma and # character around the name
with this we have created the dictionary key
Key value: int(x.split()[-1])
x.split()[-1] takes the last substring ('27')
enclosing it in int() we turn it into an integer
You can use dictionary comprehension
l = ['#David, the age is 27', '#John, the age is 99', '#rain, the age is 45']
X = {item.split(',')[0][1:]:int(item.split(',')[1].rsplit(maxsplit=1)[-1]) for item in l}
print(X)
#output
{'David': 27, 'John': 99, 'rain': 45}
road= []
distance=[]
i= input ('THE NUMBER OF NODES TO TEST')
for i in range(0,i):
a = input(' THE NODE NUMBER \n')
b= input ('ENTER NODE VALUE \n')
road.append(a)
distance.append(b)
print 'THE NODES AND RESPECTIVE VALUES ARE'
print "NODES: \t | \t VALUES:\n " ,words, distance
In above python sample code road and distance are two lists which will store the value input by the user. Now I want to add those data in a dictionary where road[0]:distance[0], road[1]: distance[1] and so on. i.e. The values inserted in the list 'road' and 'distance' should be included in a new dictionary say 'map'which is somehow like this map={"road":"distance"}
Use zip and dict built-in functions.
dict(zip(road,distance))
Example:
>>> road = ['foo', 'bar']
>>> distance = [1,2]
>>> dict(zip(road,distance))
{'foo': 1, 'bar': 2}
using zip will save your time.
But simple code is:
road = [1,2,3,4,5]
distance = [100,150,120,150,200]
dict = {}
for i in range(0, len(road)):
dict[road[i]] = distance[i]