Reputation: 13
How can I store the types of elements from a list in a dictionary? for example to make the output like this :
datatype_statistic([1,'2',3.5, 0.5, None, (1,1)]) = {
'int': 1,
'str': 1,
'float': 2,
'None':1,
'tuple': 1
}
This is what I did till now but I just do not know what is the method that I should apply to acheive the above :
def datatype_statistic(ls):
my_list=len(ls)
print("There are "+str(my_list)+" elements in this list" )
for item in ls:
print(type(item))
datatype_statistic([1,'2',3.5, 0.5, None, (1,1)])
Upvotes: 0
Views: 81
Reputation: 1
You can achieve this by using some built-in methods in Python such as map
, list.count
, and type
This is the solution for me:
your_list = [1,'2',3.5, 0.5, None, (1,1)]
x = list(map(lambda j: type(j), your_list))
types_dict = {i.__name__:x.count(i) for i in x} # A dict comprehension
# types_dict value sould be: {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}
Upvotes: 0
Reputation: 3886
collections.Counter
is specifically made for this kind of task:
from collections import Counter
ls = [1,'2',3.5, 0.5, None, (1,1)]
def datatype_statistic(ls):
type_names = [type(elem).__name__ for elem in ls]
return dict(Counter(type_names))
print(datatype_statistic(ls))
Output:
{'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}
I first use a list comprehension to get the type names from the list elements. Then I just apply the Counter
. Finally I cast to dict to get the output in the requested form.
Note that the calls to .__name__
and dict()
are only there to shoe-horn the result to fit the example given for a desired result. You need to know yourself if you actually need them.
The type of None
is NoneType
, so that's what I print. You can special-case this if needed.
Upvotes: 1
Reputation: 768
jake_list = [1, '2', 3.5, 0.5, None, (1, 1)]
datatype_statistic = dict()
for i in jake_list:
tmp_type = type(i).__name__
datatype_statistic[tmp_type] = datatype_statistic.get(tmp_type, 0) + 1
# {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}
Upvotes: 0
Reputation: 71
You would have to employ some form of counter to solve this, which you have not used in your code.
def type_counter_list(list_1):
count_type = dict()
for _ in list_1:
x = type(_)
if _ in count_type.keys():
count_type[x]+=1
else:
count_type[x]=1
return count_type
This is not a code, but I guess you are a beginner. This is a blueprint for you to develop your code on.
Upvotes: 0
Reputation: 3624
You can use collections.defaultdict
:
from collections import defaultdict
def datatypes(lst):
ret = defaultdict(int)
for x in lst:
ret[type(x).__name__] += 1
return dict(ret)
print(datatypes([1, '2', 3.5, 0.5, None, (1, 1)]))
Or, without imports:
def datatypes(lst):
ret = {}
for x in lst:
ret[type(x).__name__] = ret.get(type(x).__name__, 0) + 1
return ret
print(datatypes([1, '2', 3.5, 0.5, None, (1, 1)]))
Output: {'int': 1, 'str': 1, 'float': 2, 'NoneType': 1, 'tuple': 1}
Upvotes: 1