I got a list like this:
[['a','b','1','2']['c','d','3','4']]
and I want to convert this list to dictionary something looks like this:
{
('a','b'):('1','2'),
('c','d'):('3','4')
}
for example, ('a', 'b') & ('c','d') for key
and ('1','2') &('3','4') for value
so I used code something like this
new_dict = {}
for i, k in enumerate(li[0:2]):
new_dict[k] =[x1[i] for x1 in li[2:]]
print(new_dict)
,but it caused unhashable type error 'list'
I tried several other way, but it didn't work well..
Is there any way that I can fix it?
You can't have list as key, but tuple is possible. Also you don't need to slice on your list, but on the sublist.
You need the 2 first values sublist[:2] as key and the corresponding values is the sublist from index 2 sublist[2:]
new_dict = {}
for sublist in li:
new_dict[tuple(sublist[:2])] = tuple(sublist[2:])
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
The same with dict comprehension
new_dict = {tuple(sublist[:2]): tuple(sublist[2:]) for sublist in li}
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
li = [['a','b','1','2'],['c','d','3','4']]
new_dict = {}
for item in li:
new_dict[(item[0], item[1])] = (item[2], item[3])
I would use list-comprehension following way:
lst = [['a','b','1','2']['c','d','3','4']]
dct = dict([(tuple(i[:2]),tuple(i[2:])) for i in lst])
print(dct)
or alternatively dict-comprehension:
dct = {tuple(i[:2]):tuple(i[2:]) for i in lst}
Output:
{('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
Note that list slicing produce lists, which are mutable and can not be used as dict keys, so I use tuple to convert these to immutable tuples.
You can do it with dict comprehension:
li = [
['a', 'b', '1', '2'],
['c', 'd', '3', '4'],
]
new_dict = {(i[0], i[1]): (i[2], i[3]) for i in li}
print(new_dict)
# result
{('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
Related
I have a list like this in Python:
[('a', 'b'), ('a', 'c'),('d','f')]
and I want join items that have same first item and result like this:
[('a', 'b', 'c'),('d','f')]
Here is one way to do it. For efficiency, we build a dict with the first value as key. We keep the values in the order in which they appear (and the tuples in their original order as well, if you use Python >= 3.7 - otherwise you will have to use a collections.OrderedDict)
def join_by_first(sequences):
out = {}
for seq in sequences:
try:
out[seq[0]].extend(seq[1:])
except KeyError:
out[seq[0]] = list(seq)
return [tuple(values) for values in out.values()]
join_by_first([('a', 'b'), ('a', 'c'),('d','f')])
# [('a', 'b', 'c'), ('d', 'f')]
You can not edit tuples - the are immuteable. You can use lists and convert all back to tuples afterward:
data = [('a', 'b'), ('a', 'c'),('d','f')]
new_data = []
for d in data # loop over your data
if new_data and new_data[-1][0] == d[0]: # if something in new_data and 1st
new_data[-1].extend(d[1:]) # ones are identical: extend
else:
new_data.append( [a for a in d] ) # not same/nothing in: add items
print(new_data) # all are lists
new_data = [tuple(x) for x in new_data]
print(new_data) # all are tuples again
Output:
[['a', 'b', 'c'], ['d', 'f']] # all are lists
[('a', 'b', 'c'), ('d', 'f')] # all are tuples again
See Immutable vs Mutable types
I feel like the simplest solution is to build a dictionary in which:
keys are the first items in the tuples
values are lists comporting all second items from the tuples
Once we have that we can then build the output list:
from collections import defaultdict
def merge(pairs):
mapping = defaultdict(list)
for k, v in pairs:
mapping[k].append(v)
return [(k, *v) for k, v in mapping.items()]
pairs = [('a', 'b'), ('a', 'c'),('d','f')]
print(merge(pairs))
This outputs:
[('a', 'b', 'c'), ('d', 'f')]
This solution is in O(n) as we only iterate two times over each item from pairs.
Say, I have a two 2D list like below:
[[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
The output I want to achieve is:
Output_list=[['1','12','3'], ['21','31'], ['11']]
The main complexity here is I want to achieve the output through a single list comprehension.
One of my attempts was:
print [a for innerList in fin_list1 for a,b in innerList]
Output:
['1', '12', '3', '21', '31', '11']
But, as you can see, though I have successfully retrieve the second elements of each tuple, i failed to retain my inner list structure.
We start with this:
>>> l = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
Initially you tried to do something along these lines:
>>> [y for sublist in l for x, y in sublist]
['1', '12', '3', '21', '31', '11']
The mistake here is that this list comprehension is one-dimensional, i.e. all the values will be just integers instead of lists themselves
In order to make this two-dimensional, our values need to be lists. The easiest way to do this is by having our value expression be a nested list comprehension that iterates over the elements of the sublists of the original list:
>>> [[y for x, y in sublist] for sublist in l]
[['1', '12', '3'], ['21', '31'], ['11']]
Technically this is two list comprehensions, but obviously a list comprehension can be replaced by map as explained in Roberto's answer.
First, let's assign the data:
>>> data = [
[('a', '1'), ('a', '12'), ('a', '3')],
[('b', '21'), ('b', '31')],
[('c', '11')],
]
You can use itemgetter to create a function that gets one element from the tuple:
>>> from operator import itemgetter
>>> first = itemgetter(0)
>>> second = itemgetter(1)
Now you can transform inner lists by using map:
>>> [map(first, row) for row in data]
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>> [map(second, row) for row in data]
[['1', '12', '3'], ['21', '31'], ['11']]
You could also create first and second without using itemgetter:
def first(xs):
return xs[0]
def second(xs):
return xs[1]
the_list = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
new_list = [[x[1] for x in y] for y in the_list]
print new_list
Output:
[['1', '12', '3'], ['21', '31'], ['11']]
I am trying to iterate over a Python 2D list. As the algorithm iterates over the list, it will add the key to a new list until a new value is detected. An operation is then applied to the list and then the list is emptied so that it can be used again as follows:
original_list = [('4', 'a'), ('3', 'a'), ('2', 'a'), ('1', 'b'), ('6', 'b')]
When the original_list is read by the algorithm it should evaluate the second value of each object and decipher if it is different from the previous value; if not, add it to a temporary list.
Here is the psedo code
temp_list = []
new_value = original_list[0][1] #find the first value
for key, value in original_list:
if value != new_value:
temp_list.append(new_value)
Should output
temp_list = ['4', '3', '2']
temp_list = []
prev_value = original_list[0][1]
for key, value in original_list:
if value == prev_value:
temp_list.append(key)
else:
do_something(temp_list)
print temp_list
temp_list = [key]
prev_value = value
do_something(temp_list)
print temp_list
# prints ['4', '3', '2']
# prints ['1', '6']
Not entirely sure what you are asking, but I think itertools.groupby could help:
>>> from itertools import groupby
>>> original_list = [('4', 'a'), ('3', 'a'), ('2', 'a'), ('1', 'b'), ('6', 'b')]
>>> [(zip(*group)[0], k) for k, group in groupby(original_list, key=lambda x: x[1])]
[(('4', '3', '2'), 'a'), (('1', '6'), 'b')]
What this does: It groups the items in the list by their value with key=lambda x: x[1] and gets tuples of keys corresponding to one value with (zip(*group)[0], k).
In case your "keys" do not repeat themselves, you could just use a defaultdict to "sort" the values based on keys, then extract what you need
from collections import defaultdict
ddict = defaultdict(list)
for v1, v2 in original_list:
ddict[v2].append(v1)
ddict values are now all temp_list:
>>> ddict["a"]
['4', '3', '2']
I've created a dictionary from a tuple, but can't seem to find an answer as to how I'd switch my keys and values without editing the original tuple. This is what I have so far:
tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')]
dic = dict(tuples)
print dic
This gives the output:
{'a': '1', 'b': ''1', 'c': '2', 'd': '3'}
But I'm looking for:
{'1': 'a' 'b', '2': 'c', '3': 'd'}
Is there a simple code that could produce this?
Build a dictionary in a loop, collecting your values into lists:
result = {}
for value, key in tuples:
result.setdefault(key, []).append(value)
The dict.setdefault() method will set and return a default value if the key isn't present. Here I used it to set a default empty list value if the key is not present, so the .append(value) is applied to a list object, always.
Don't try to make this a mix of single string and multi-string list values, you'll only complicate matters down the road.
Demo:
>>> tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')]
>>> result = {}
>>> for value, key in tuples:
... result.setdefault(key, []).append(value)
...
>>> result
{'1': ['a', 'b'], '3': ['d'], '2': ['c']}
from operator import itemgetter
from itertools import groupby
first = itemgetter(0)
second = itemgetter(1)
d = dict((x, [v for _, v in y]) for x, y in groupby(sorted(tuples, key=second), key=second)
groupby groups the tuples into a new iterator of tuples, whose first element is the unique second item of each of the original, and whose second element is another iterator consisting of the corresponding first items. A quick example (pretty-printed for clarity):
>>> list(groupby(sorted(tuples, key=second), key=second)))
[('1', <itertools._grouper object at 0x10910b8d0>),
('2', <itertools._grouper object at 0x10910b790>),
('3', <itertools._grouper object at 0x10910b750>)]
The sorting by the same key used by groupby is necessary to ensure all like items are grouped together; groupby only makes one pass through the list.
The subiterators consist of tuples like ('1', 'a'), so the second value in each item is the one we want to add to the value in our new dictionary.
Using the key-pair tuples from my_file.txt, create a dictionary. If a key exists multiple times with different values, use the first seen value
(e.g., the first instance we encountered the key).
my_file = [('a', '1')
('b', '2')
('c', '3')
('d', '4')
('e', '5')]
def makehtml(fname):
with open(fname) as f: # reads lines from a fname file
for line in f:
tups = line2tup(line,"--") # turns each line into a 2 elem tuple on it's own line.
print tups
How can I create a dictionary from my_file key/value pairs. I've tried dict(my_file), but it's telling me that "ValueError: dictionary update sequence element #0 has length 1; 2 is required".
The dict constructor accepts a list of tuples as a parameter:
>>> my_file = [('a', '1'),
('b', '2'),
('c', '3'),
('d', '4'),
('e', '5')]
>>> dict(my_file)
{'e': '5', 'd': '4', 'c': '3', 'b': '2', 'a': '1'}
Edit: ahh, i got your problem. Assuming your file looks like this:
('a', '1')
('b', '2')
('c', '3')
('d', '4')
('e', '5')
Then this should work:
def makehtml(fname):
with open(fname) as f:
d = {}
for line in f:
key, value = line2tup(line,"--")
d[key] = value
return d
How about this:
mydict = {}
for line in open(fname):
k, v = line.split()
mydict[int(k)] = v