I have a list of strings like this:
l = ['ABC, Apple, 20021015, 20030102', 'CDE, Graps, 20020506, 20030130']
I want to convert this list to a dictionary like
d = { 'ABC': 'Apple', 'CDE': 'Graps' }
So the key would be the first name in the string and the value would be the second name in the string.
This works in Python 2:
d = {j[0]:j[1] for j in [i.split(', ') for i in l]}
Output:
{'CDE': 'Graps', 'ABC': 'Apple'}
You could do it like this:
for index in range(len(l)):
line = l[index].split(", ")
d[line[0]] = line[1]
So, you split each entry by commas to get each name and date individually, and then you can add them each to the dict as normal.
Alternative, shorter form:
>>> dict(x.split(', ')[:2] for x in l)
{'ABC': 'Apple', 'CDE': 'Graps'}
This works by passing a sequence of two-element lists to dict() which then initializes the dictionary based on that sequence. The sequence being passed is this:
>>> [x.split(', ')[:2] for x in l]
[['ABC', 'Apple'], ['CDE', 'Graps']]
Related
How to create a dictionary from a string composed by space separated words with i for i in range(0, n) as key in the dictionary ?
Tried this:
i = 0
map(dic[i+=1],input().split())
It didn't work.
It should output this:
dic={0:'apple',1:'grapes',2:'orange',3:'banana'}
input_str = "Hello world"
result = {key: value for key, value in enumerate(input_str.split())}
print(result)
Output:
{0: 'Hello', 1: 'world'}
But you can use a list since this data structure is made for iterating over their contents and keeps order. If you want an int as key, just use enumerate(your_list).
In Python, when to use a Dictionary, List or Set?
You could use enumerate:
d = {}
for i, v in enumerate(input().split()):
d[i] = v
Or simply:
d = dict(enumerate(input().split()))
But why do that? use a list...
Since your keys are simply (ordered!) integers, using a dict seems an overkill as to access integer-indexed values from a list is also O(1). For example, let's look at a small comparison with the 2 versions:
l = input().split()
d = dict(enumerate(l))
We have:
>>> print(l)
['apple', 'orange', 'banana']
>>> print(d)
{0: 'apple', 1: 'orange', 2: 'banana'}
Now let's see how we will grab values:
>>> l[0]
'apple'
>>> d[0]
'apple'
>>> l[2]
'banana'
>>> d[2]
'banana'
Dictionaries have a small memory overhead and so for this case using a dictionary doesn't give any advantage.
input_ = input("enter your fruits:").split(' ')
print (dict(zip([*range(len(input_))], input_)))
# print (dict(enumerate(input_)))
output:
enter your fruits:banana kiwi orange apple
{0: 'banana', 1: 'kiwi', 2: 'orange', 3: 'apple'}
I want to count the number of times a string has occurred in a list which is in another list and store it in a list of dictionary where each dictionary has count of a list.
Ex,
list = [['Sam','John','Alex','Sam','Alex'],['Max','Sam','Max']...]
and I want my list of dictionaries to be like:
count_list = [{'Sam':2,'Alex':2,'John':1}, {'Max':2, 'Sam':1}..]
I am iterating through each list to count number of times each string has occurred and adding each result to dict. But I end up having different result every time and not the correct values.
count_list = []
for l in list :
d = {}
for str in l:
if str not in d:
d[str] = l.count(str)
count_list.append(d)
Any help would be useful.Thanks.
It would be easier to use collections.Counter() here:
>>> from collections import Counter
>>> lst = [["Sam", "John", "Alex", "Sam", "Alex"], ["Max", "Sam", "Max"]]
>>> list(map(Counter, lst))
[Counter({'Sam': 2, 'Alex': 2, 'John': 1}), Counter({'Max': 2, 'Sam': 1})]
You could also use a list comprehension instead of using map() if thats easier to understand:
>>> [Counter(l) for l in lst]
[Counter({'Sam': 2, 'Alex': 2, 'John': 1}), Counter({'Max': 2, 'Sam': 1})]
Note: Counter is a subclass of dict, so you can treat them like normal dictionaries.
You can always cast to dict() if you want to as well:
>>> [dict(Counter(l)) for l in lst]
[{'Sam': 2, 'John': 1, 'Alex': 2}, {'Max': 2, 'Sam': 1}]
You should also not use list as a variable name, since it shadows the builtin function list().
Currently, you are doing the following:
count_list = []
for l in list :
d = {}
for str in l:
if str not in d:
d[str] = l.count(str)
count_list.append(d)
Note that you are appending the dictionary for each string in the sub lists, rather than one dictionary per sub list.
Doing the following should address the issue:
count_list = []
for l in list :
d = {}
for str in l:
if str not in d:
d[str] = l.count(str)
count_list.append(d)
i have used list comprehensions not very often but i was wondering if the below lines can be a one liner (yes the code is already small, but i am curious):
lst = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
for index in lst:
data[index] = data.get(index,0) + 1
data would be: {'hi':1, 'hello':3, 'bob':2}
something:
d = { ... for index in lst } ????
I have tried some comprehensions but they don't work:
d = { index:key for index in lst if index in d: key = key + 1 else key = 1 }
Thanks in adv.
Simply use collections.Counter
A Counter is a dict subclass for counting hashable objects. It is an
unordered collection where elements are stored as dictionary keys and
their counts are stored as dictionary values. Counts are allowed to be
any integer value including zero or negative counts. The Counter class
is similar to bags or multisets in other languages.
import collections
l = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
c = collections.Counter(l)
assert c['hello'] == 3
I am trying to create a list of lists based on hashes. That is, I want a list of lists of items that hash the same. Is this possible in a single-line comprehension?
Here is the simple code that works without comprehensions:
def list_of_lists(items):
items_by_hash = defaultdict(list)
for item in items:
words_by_key[hash(item)].append(item)
return words_by_key.values()
For example, let's say we have this simple hash function:
def hash(string):
import __builtin__
return __builtin__.hash(string) % 10
Then,
>>> l = ['sam', 'nick', 'nathan', 'mike']
>>> [hash(x) for x in l]
[4, 3, 2, 2]
>>>
>>> list_of_lists(l)
[['nathan', 'mike'], ['nick'], ['sam']]
Is there any way I could do this in a comprehension? I need to be able to reference the dictionary I'm building mid-comprehension, in order to append the next item to the list-value.
This is the best I've got, but it doesn't work:
>>> { hash(word) : [word] for word in l }.values()
[['mike'], ['nick'], ['sam']]
It obviously creates a new list every time which is not what I want. I want something like
{ hash(word) : __this__[hash(word)] + [word] for word in l }.values()
or
>>> dict([ (hash(word), word) for word in l ])
{2: 'mike', 3: 'nick', 4: 'sam'}
but this causes the same problem.
[[y[1] for y in x[1]] for x in itertools.groupby(sorted((hash(y), y)
for y in items), operator.itemgetter(0))]
I got a list of object
lst = [1,2,3]
I want them in a dictionary with a default key 'number', and then put them in a list.
The result should look like
lst = [{'number':1},{'number':2},{'number':3}
Use less code, please.
Use a list comprehension
lst = [{'number': x} for x in lst]
This matches your code samples:
>>> lst = [1,2,3]
>>> newlst = [dict(number=n) for n in lst]
>>> newlst
[{'number': 1}, {'number': 2}, {'number': 3}]
>>>
What you say, however, is a bit different - you want them all in the same dictionary, or each in a dictionary of its own? The snippet above gives you the latter.