I have one dataset in a list form and I want to convert it into another dataset under certain conditions.
Conditions
"a" = 1
"b" = 2
"c" = 3
input_list = ["a", "b", "c"]
# something happens
output_list = [1, 2, 3]
What to do?
Represent your set of conditions in a dictionary:
conditions = {
"a": 1,
"b": 2,
"c": 3
}
Use that dictionary in order to generate the output:
input_list = ["a", "b", "c"]
output_list = [conditions[x] for x in input_list]
What you want to achieve is a mapping.
Your conditions are a map, dictionary (Python lingo) or hash-table.
Each value there (like 1) corresponds to a key in the dataset (like "a").
To represent this mapping you can use a table-like datastructure that maps a key to a value. In Python this datastructure is called a dictionary:
mapping = {"a": 1, "b": 2, "c": 3} # used to translate from key to value (e.g. "a" to 1)
input_list = ["a", "b", "c"]
# something happens
output_list = []
for v in input_list:
mapped_value = mapping[v] # get the corresponding value, translate or map it
print(v + " -> " + mapped_value)
output_list.append(mapped_value)
print(output_list) # [1, 2, 3]
See also
Map (mathematics) - Wikipedia
Convert numbers into corresponding letter using Python
Related
This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 10 months ago.
i was trying to keep count of each item in list in python and want to convert it into key-value pairs like json so i can able to iterate over it to present it on frontend using django.
list = ["a" , "a", "c", "b", "c", "d"]
here same i want this list into key value pairs with counting of each item in list
list = [{ "name":"a" , "count":2 } , { "name":"c" , "count":2 , ......}]
Use a set to count the number of each element in the list
l = ["a" , "a", "c", "b", "c", "d"]
d = {val: l.count(val) for val in set(l)}
this will give you :
{'c': 2, 'a': 2, 'b': 1, 'd': 1}
If you want to format the dict as you wrote it in your message (even though it's really inefficient), you can write it like that :
d = [{'name': val, 'count': l.count(val)} for val in set(l)}]
data = ["a" , "a", "c", "b", "c", "d"]
count_list=[{"name":d,"count": data.count(d)} for d in set(data)]
Probably the easiest way to do this:
def dict_count(list):
dict_tot = {}
for i in liste:
dict_tot[i] = liste.count(i)
print(dict_tot)
test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
data = test.count(search)
data
When I run this, I get
TypeError: must be str, not list
I want to know how I can count when using [ ] instead of a single string.
you can use a loop on search
data = [test.count(s) for s in search]
count() takes a str parameter and not a list.
test = "aaaabbcdeiiifkdkkffkk"
data = test.count("a")
More info here.
You need to loop throught the search list, so this list comprehension can do the job:
[test.count(i) for i in search]
But i prefer this
test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
data = {}
for i in search:
data.update({i: test.count(i)})
Or you can use a one liner.
data = {c: test.count(c) for c in search}
Out: {'a': 4, 'c': 1, 'd': 2, 'e': 1}
You can use multiple ways to find out, to count the number of occurrence, .count() only takes one str value
Method 1: Using List Comprehension
data = [test.count(s) for s in search]
Method 2: Using Map
data = list(map(test.count,search))
You can create multiple other methods to do so referring the above.
Using collections.Counter
Ex:
from collections import Counter
test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
count_data = Counter(test) #--> Counter({'k': 5, 'a': 4, 'i': 3, 'f': 3, 'b': 2, 'd': 2, 'c': 1, 'e': 1})
for i in search:
print(i, count_data.get(i, 0))
Output:
a 4
c 1
d 2
e 1
Loop over search strings and apply count to each one.
data = []
pos = 0
for s in search:
data[pos] = test.count(s)
pos = pos + 1
print(data)
Let's say I have a 2D list in Python:
mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). At the end of my consolidation the output should consolidate the keys and count the unique occurrences of values present for each key, i.e. something like:
# Output
# {"A":{"X":2, "Y":2}, "B":{"X":2, "Y":1}}
I am trying to use Python's itertools.groupby, but to no avail. Something similar to this question. If you have a better method, let me know.
Thanks!
I think the easiest way to do this would be with Counter and defaultdict:
from collections import defaultdict, Counter
output = defaultdict(Counter)
for a, b in mylist:
output[a][b] += 1
L3viathan's answer seems to be better. However, this is another approach:
mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
dictionary = {"A": {"X": 0, "Y": 0}, "B": {"X": 0, "Y": 0}}
for x in mylist:
dictionary[x[0]][x[1]] += 1
Lets say I have a dictionary like this:
myDict = {
1: {
"a": "something",
"b": [0, 1, 2],
"c": ["a", "b", "c"]
},
2: {
"a": "somethingElse",
"b": [3, 4, 5],
"c": ["d", "e", "f"]
},
3: {
"a": "another",
"b": [6, 7, 8],
"c": ["g", "h", "i"]
}
}
And this is my code:
for id, obj in myDict.items():
for key, val in obj.items():
if key is "b":
for item in val:
# apply some function to item
Is there a better way to iterate over a list inside a nested dict? Or is there a pythonic way to do this?
You absolutely do not need to iterate the list to print it (unless this is a functional requirement for the code you are writing).
Very simply, you could do this:
for id, obj in myDict.items():
if "b" in obj:
print obj["b"]
To map the list object, represented by obj['b'] to another function, you can use the map function:
map(foo, obj["b"])
If you're dictionary is always two levels deep, I don't see anything wrong with your approach. In your implementation, I would use key == "b" rather than key is "b". Using is will test for identity (e.g. id(a) == id(b)), while == will test for equality (e.g. a.__eq__(b)). This functions the same way when I test it in IDLE, but it's not a good habit to get into. There's more info on it here: How is the 'is' keyword implemented in Python?
If you want to deal with varying level dictionaries, you could use something like:
def test_dict_for_key(dictionary, key, function):
for test_key, value in dictionary.items():
if key == test_key:
dictionary[key] = type(value)(map(function, value))
if isinstance(value, dict):
test_dict_for_key(value, key, function)
An example usage might be something like:
myDict = {
1: {
"a": "something",
"b": [0, 1, 2],
"c": ["a", "b", "c"]
},
2: {
"a": "somethingElse",
"b": [3, 4, 5],
"c": ["d", "e", "f"]
},
3: {
"a": "another",
"b": [6, 7, 8],
"c": ["g", "h", "i"]
}
}
# adds 1 to every entry in each b
test_dict_for_key(myDict, "b", lambda x: x + 1)
# prints [1, 2, 3]
print(myDict[1]["b"])
I'm a fan of generator expressions.
inner_lists = (inner_dict['b'] for inner_dict in myDict.values())
# if 'b' is not guaranteed to exist,
# replace inner_dict['b'] with inner_dict.get('b', [])
items = (item for ls in inner_lists for item in ls)
Now you can either use a foo loop
for item in items:
# apply function
or map
transformed_items = map(func, items)
A couple fixes could be made.
Don't use is when comparing two strings (if key is "b":)
Simply say print(item) instead of using .format(), since you only have one variable that you're printing, with no additional string formatting
Revised code:
for id, obj in myDict.items():
for key, val in obj.items():
if key == "b":
for item in val:
print(item)
If you are sure that you will have a b key in every case, you can simply do:
for id, obj in myDict.items():
for item in obj["b"]:
print item
I have a dict with a dynamical number of nested dicts inside of it, something like:
my_dict = {"a": {"b": {"c: {...}}}}
I need to dynamically move inside this dict, for instance I'd like to do the following:
levels = ["a", "b", "c"]
my_dict[levels[0]][levels[1]][levels[2]] = "something"
where the number of items inside "levels" may vary.
I can partially achieve the same result for a limited number of items inside "levels" by writing something like this:
if len(levels) == 1:
my_dict[levels[0]] = "something"
elif len(levels) == 2:
my_dict[levels[0]][levels[1]] = "something"
elif len(levels) == 3:
my_dict[levels[0]][levels[1]][levels[2]] = "something"
(...)
but I'm looking for a more general and elegant solution.
Is there a way to do this?
There isn't a lot of code here to go on, but for what you have given, you can define
def get(d, keys):
for key in keys:
d = d[key]
return d
def set(d, keys, value):
d = get(d, keys[:-1])
d[keys[-1]] = value
And then use it like this
my_dict = {"a":{"b":{"c":{}}}}
set(my_dict, ["a", "b", "c"], "something")
print get(my_dict, ["a", "b", "c"])
A functional alternative for get:
def get(d, keys):
return reduce(lambda d, key: d[key], keys, d)