This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I am trying to figure out how to best create a python dictionary where the values are variable names
e.x.
ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]
for i in ruleLst:
new_values = i.split("+")
rules.update({i:new_values})
rules
returns:
{
'gender+brand': ['gender', 'brand'],
'sport+gender': ['sport', 'gender'],
'sport+gender+brand': ['sport', 'gender', 'brand']
}
What I try to output is:
{
'gender+brand': [gender, brand],
'sport+gender': [sport, gender],
'sport+gender+brand': [sport, gender, brand]
}
Where gender, brand, sport are lists defined in the code before ruleLst is defined.
You can use list comprehension like:
ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]
gender = ["M", "F"]
sport = ["basket", "volleyball"]
brand = [1, 2]
a = {i: [globals()[j] for j in i.split("+")] for i in ruleLst}
print(a)
and output:
{
'gender+brand': [['M', 'F'], [1, 2]],
'sport+gender': [['basket', 'volleyball'], ['M', 'F']],
'sport+gender+brand': [['basket', 'volleyball'], ['M', 'F'], [1, 2]]
}
Reference:
Create a dictionary with list comprehension
How to get the value of a variable given its name in a string?
Try using globals()[new_values[0]] and globals()[new_values[1]] instead of new_values to get the variables value.
Like this:
ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]
rules = {}
gender = ["male", "female"]
sport = ["basket", "volleyball"]
brand = ["x", "y"]
for i in ruleLst:
new_values = i.split("+")
rules.update({i:[globals()[new_values[0]], globals()[new_values[1]]]})
print(rules)
You could solve this with the map function like this. By casting it as a dict you'll get the dictonary you want.
rules = dict(map(lambda elem: [elem, elem.split('+')], ruleLst))
Related
This question already has answers here:
Sort a list with a custom order in Python
(4 answers)
Closed 2 months ago.
I have a list of objects like this:
my_list = [obj1,obj2,obj3, ...]
Each object has some data like:
obj = {
'id':1,
'name':'Some name',
'value': 'Some value',
'category':'A'
}
The category options are: CATEGORY = {'A','B','C','D'}
Is it possible to sort the list somehow to display data in sequence like:
my_sordet_list = ['all in C categ', 'all in B categ', 'all in D categ','all in A categ']
So the question is: How can I explain to the program that I want it to be sorted in a strict custom sequence?
You could create a lookup dictionary for your custom ordering:
>>> category_order = {'C': 0, 'B': 1, 'D': 2, 'A': 3}
>>> my_sorted_list = sorted(mylist, key=lambda o: category_order[o['category']])
my_sorted_list will be sorted, as you desire.
This question already has answers here:
How can I get the name of an object?
(18 answers)
Closed 1 year ago.
I'm wondering if something like this is possible. Let's suppose this snippet of code:
area = ["A","B","C"]
level = ["L1","L2","L3"]
sector = [area, level]
print(sector)
print(sector[1])
Output:
Print 1: [['A', 'B', 'C'], ['L1', 'L2', 'L3']]
Print 2: ['L1', 'L2', 'L3']
The first print is OK for me. It shows the lists and their elements.
However, for the second print I would like to have the name of the list instead of its elements. In this case level
Is that possible?
What you can do though, is use a dictionnary:
di = {"area": ["A", "B", "C"], "level": ["L1", "L2", "L3"]}
di["area"]
Output :
["A", "B", "C"]
You could compare the id:
for sec in sector:
if id(sec) == id(area):
print('area')
elif id(sec) == id(level):
print('level')
etc.
However, this is a dubious way to go. Why do you need this?
Make it into a Dictionary of Lists instead of a List of Lists:
area = ["A","B","C"]
level = ["L1","L2","L3"]
sectors = {
"area": area,
"level": level
}
print(sectors["level"])
print(sectors["area"])
""" some other useful dict methods below """
print(sectors.keys())
print(sectors.values())
print(sectors.items())
You can use a dictionary for your usecase.
You can make the name of the variables as key and lists as values.
Try this:
area = ["A","B","C"]
level = ["L1","L2","L3"]
sector = {"area":area, "level":level}
print(list(sector.values()))
print(list(sector.keys()))
Outputs:
[['A', 'B', 'C'], ['L1', 'L2', 'L3']]
['area', 'level']
This question already has answers here:
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
Closed 1 year ago.
I have a list of variables like:
master = ['A', 'B', 'C', 'D']
I want to loop over master and create n lists where n is number of variables.
Also the names of the lists should be by the name of the elements
I tried:
for i in master:
i = list()
print(i)
but here the list doesn't have any name
If you want to assign a name (that is the same as the element), you probably need a dictionary.
from collections import defaultdict
master = ['A', 'B', 'C', 'D']
d = defaultdict(list)
for elem in master:
d[elem].append(elem)
print(d["A"]) # ["A"]
You can also do this with dict-comprehension.
d1 = {el: el for el in master}
print(d1["A"]) # "A"
d2 = {el: [el] for el in master}
print(d2["A"]) # ["A"]
You can use python dictionaries for this . For example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
this will print {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Please visit here for more explanations : here
This question already has answers here:
Reverse / invert a dictionary mapping
(32 answers)
Closed 2 years ago.
id_dict = {1 : 'cat', 2 : 'dog', 3 : 'fish', 4 : 'cow' }
feature_list = ['cat','cat', 'dog', 'dog','fish', 'calf']
id_list = ['nan','nan','nan','nan','nan', 'nan']
for key, value in id_dict.items():
for item in feature_list:
if item == value:
id_list[feature_list.index(value)] = key
How can I make sure that the id_list is updated with [1,1,2,2,3] when the values match and pass over when a value is not in there ? Currently, only the first value is being updated.
Current Output: [1, 'nan', 2, 'nan', 3]
Your id_dict is backwards of what is useful for you:
id_dict = {1 : 'cat', 2 : 'dog', 3 : 'fish' }
feature_list = ['cat','cat', 'dog', 'dog','fish']
# id_list = ['nan','nan','nan','nan','nan']
# Swap the keys and values (ideally change the starting dictionary)
id_dict = {val: key for key, val in id_dict.items()}
# Create your id_list
id_list = [id_dict[ele] for ele in feature_list]
If you need to handle values that are not in id_dict then you have several different options.
To apply a default:
id_list = [id_dict.get(ele, 'Default value') for ele in feature_list]
If you want to skip values that are not contained within id_dict:
id_list = [id_dict[ele] for ele in feature_list if ele in id_dict]
This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 4 years ago.
I have a list that looks like this:
mylist = [1, 'a', 2, 'b', 3, 'c']
and would like to end up with a dictionary:
mydict = {
'a': 1,
'b': 2,
'c': 3,}
At the moment I'm achieving it like so:
mydict = {}
for i, k in enumerate(mylist):
if i == len(mylist)/2:
break
v = 2 * i
mydict[mylist[v+1]] = mylist[v]
Is there a more pythonic way of achieving the same thing? I looked up the itertools reference but didn't find anything in particular that would help with the above.
Note: I'm happy with what I have in terms of achieving the goal, but am curious if there is anything that would be more commonly used in such a situation.
Try this
# keys
k = mylist[1::2]
# values
v = mylist[::2]
# dictionary
mydict = dict(zip(k, v))