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']
Related
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))
I'm trying to find the values of keys based on their 3 first letters. I have three different categories of subjects that i have to get the grade from, stored as value with the subject being key. I have ECO, GEO, and INF. As there are multiple subjects i want to get the values from every key containing either ECO, GEO or INF.
subject={"INFO100":"A"}
(subject.get("INF"))
In this method i don't get the value, i have to use the whole Key. Is there a work-a-round? I want the values seperately so i can calculate their GPA based on their field of study:)
You need to iterate on the pairs, to filter on the key and keep the value
subject = {"INFO100": "A", "INF0200": "B", "ECO1": "C"}
grades_inf = [v for k, v in subject.items() if k.startswith("INF")]
print(grades_inf) # ['A', 'B']
grades_eco = [v for k, v in subject.items() if k.startswith("ECO")]
print(grades_eco) # ['C']
A said in the comments, the purpose of a dictionary is to have unique keys. Indexing is extremely fast as it uses hash tables. By searching for parts of the keys you need to loop and lose the benefit of hashing.
Why don't you store your data in a nested dictionary?
subject={'INF': {"INFO100":"A", "INFO200":"B"},
'OTH': {"OTHER100":"C", "OTHER200":"D"},
}
Then access:
# all subitems
subject['INF']
# given item
subject['INF']['INFO100']
For understanding porpoises, you can create a function that returns a dictionary, like:
def getGradesBySubject(dict, search_subject):
return [grade for subject,grade in dict.iteritems() if subject.startwith(search_subject)]
I'd suggest using a master dict object that contains a mapping of the three-letter subjects like ECO, GEO, to all subject values. For example:
subject = {"INFO100": "A",
"INFO200": "B",
"GEO100": "D",
"ECO101": "B",
"GEO003": "C",
"INFO101": "C"}
master_dict = {}
for k, v in subject.items():
master_dict.setdefault(k[:3], []).append(v)
print(master_dict)
# now you can access it like: master_dict['INF']
Output:
{'INF': ['A', 'B', 'C'], 'GEO': ['D', 'C'], 'ECO': ['B']}
If you want to eliminate duplicate grades for a subject, or just as an alternate approach, I'd also suggest a defaultdict:
from collections import defaultdict
subject = {"INFO100": "A",
"INFO300": "A",
"INFO200": "B",
"GEO100": "D",
"ECO101": "B",
"GEO003": "C",
"GEO102": "D",
"INFO101": "C"}
master_dict = defaultdict(set)
for k, v in subject.items():
master_dict[k[:3]].add(v)
print(master_dict)
defaultdict(<class 'set'>, {'INF': {'B', 'A', 'C'}, 'GEO': {'D', 'C'}, 'ECO': {'B'}})
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
Something like :
departement = {
'departement :': [str(x) for x in depart_noms],
'formation': [str(x) for x in formations]
}
I want to do this to generate a json file except my data is in arrays
I want to build a struct like:
[{"departement": "Économique",
"formations": [
{"nom": "Bachelier en informatique de gestion",
"modules": [ { "accr": "INAF0001-2",
"lien": "/cocoon/cours/INAF0001-2.html" },
{ "accr": "INAB0002-1",
"lien": "/cocoon/cours/INAB0002-1.html" },
]}
}]
Is that possible to make in a single object variable for all data ?
Here's an example of your code with some simple lists as additional input:
depart_noms = ['a', 'b', 'c']
formations = ['x', 'y', 'z']
departement = {
'departement :': [{str(x) for x in depart_noms}],
'formation': [{str(x) for x in formations}]
}
This is perfectly valid Python, but this leads to a structure that can't be JSON serialized because it contains sets (due to the curly braces), which can't be represented in JSON. If you try to execute json.dumps(departement), you'll get the error:
TypeError: Object of type set is not JSON serializable
If instead, your code is this:
import json
depart_noms = ['a', 'b', 'c']
formations = ['x', 'y', 'z']
departement = {
'departement :': [str(x) for x in depart_noms],
'formation': [str(x) for x in formations]
}
print(json.dumps(departement))
Your resuilt will be this:
{"departement :": ["a", "b", "c"], "formation": ["x", "y", "z"]}
I'm just taking a stab at this somehow answering your question. If not, then please provide more information to better define what your problem is.
I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it.
I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the items in the sub-sublists, but that returns a list with the first sublists ([["a", "b", "c"], ["a", "b", "f"]] instead of a list with the contents of those sublists. I'm pretty sure I'm just thinking about this wrong, since I'm new to list comprehensions and Python.
Anyone have a good way to do this? (and yes, I know the names I chose (lx, li) are horrible)
Thanks.
This will give you the list you want:
[lx for li in fieldlist for lx in li[1] if li[1]]
A Pythonic solution would be something like:
>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
... for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 1})
List comprehension:
>>> s = [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
>>> [x for y, z in s for x in z]
['a', 'b', 'c', 'a', 'b', 'f']
>>>
What is the purpose of your if li[1]? If li[1] is an empty list or other container, the test is redundant. Otherwise you should edit your question to explain what else it could be.