For example i have dict python
dict = {'a': '1', 'b': '2', 'c': '3'}
and array
arr = ['4', '5', '6']
I want add sequential value array to dict
dict1 = {'a': '4', 'b': '5', 'c': '6'}
Please suggest a specific solution.
>>> d = {'a': '1', 'b': '2', 'c': '3'}
>>> arr = ['4', '5', '6']
>>> dict(zip(sorted(d), arr))
{'a': '4', 'c': '6', 'b': '5'}
You can use zip:
>>> import string
>>> arr = ['4', '5', '6']
>>> # dict(zip(sorted(original_dict), arr))
>>> dict(zip(string.ascii_lowercase, arr))
{'b': '5', 'c': '6', 'a': '4'}
BTW, don't name a varialbe dict. It will shadows builtin type/function dict.
Not sure what you are trying to do, but the below code snippet does what you intend in your question.
import os
dict = {'a': '1', 'b': '2', 'c': '3'}
arr = ['4', '5', '6']
dict1 = {}
dictAsList = dict.items()
i = 0
for key in sorted(dict):
try:
dict1[key] = arr[i]
except:
pass
i = i+1
print dict1
Python dictionary doesn't have order. So I don't get what sequential means in dictionary.
If you just want to set all value to another value you can do like this.
d = {'a': '1', 'b': '2', 'c': '3'}
arr = ['4', '5', '6']
print dict(zip(d.keys(), arr))
#{'a': '4', 'c': '5', 'b': '6'}
If you want to set value as same order you can do like this.(You need change your data structure)
from collections import OrderedDict
d = OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])
arr = ['4', '5', '6']
print dict(zip(d.keys(), arr))
#{'a': '4', 'c': '6', 'b': '5'}
Related
Suppose, there is a dictionary like
my_dict = {'A': {'5', '7', '9', '3'},
'B': {'4', '8','3'},
'C': {'5', '3', '2', '9'},
'D': {'1','6', '8','3'},
'E': {'4','3','5'}}
Now the output should be like {A,C} because they have most number of common values.
dct = {'A': {'5', '7', '9', '3'}, 'B': {'4', '8','3'}, 'C': {'5', '3', '2', '9'}, 'D': {'1','6', '8','3'}, 'E': {'4','3','5'}}
ans = [None, None]
mx = 0
for i in dct:
for j in dct:
if i != j and len(dct[i].intersection(dct[j])) > mx:
ans = [i, j]
mx = len(dct[i].intersection(dct[j]))
As there are sets contained, to find number of common elements, we have intersection method.
>>> ans
['A', 'C']
Although, its worth noting that this code would always produce a pair. If you want more number of elements, the number of loops is going to increase accordingly.
This question already has answers here:
How to zip two differently sized lists, repeating the shorter list?
(15 answers)
Closed 4 years ago.
I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.
As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].
L1 = ['A', 'B', 'C', 'D', 'E']
L2 = ['1', '2', '3']
D = dict(zip(L1, L2))
print(D)
As expected, the output is this:
{'A': '1', 'B': '2', 'C': '3'}
What I would like to achieve is the following:
{'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Use itertools.cycle to cycle around to the beginning of L2:
from itertools import cycle
dict(zip(L1, cycle(L2)))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
In your case, concatenating L2 with itself also works.
# dict(zip(L1, L2 * 2))
dict(zip(L1, L2 + L2))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Use itertools.cycle:
from itertools import cycle
L1 = ['A', 'B', 'C', 'D', 'E']
L2 = ['1', '2', '3']
result = dict(zip(L1, cycle(L2)))
print(result)
Output
{'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}
As an alternative you could use enumerate and index L2 modulo the length of L2:
result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
print(result)
cycle is fine, but I shall add this modulo based approach:
{x: L2[i % len(L2)] for i, x in enumerate(L1)]}
You can also use a collections.deque() to create an circular FIFO queue:
from collections import deque
L1 = ['A', 'B', 'C', 'D', 'E']
L2 = deque(['1', '2', '3'])
result = {}
for letter in L1:
number = L2.popleft()
result[letter] = number
L2.append(number)
print(result)
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.
Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.
Other option without dependencies with good old for loop:
D = {}
for i, e in enumerate(L1):
D[e] = L2[i%len(L2)]
D #=> {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Or just:
{ e: L2[i%len(L2)] for i, e in enumerate(L1) }
#=> {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
This question already has answers here:
List of dicts to/from dict of lists
(14 answers)
Closed 4 years ago.
so given a list of dictionaries:
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'},
{'a': '1', 'b': '8', 'c': '1', 'd': '2'},
{'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
and a list of keys in the dictionary for example [ 'a', 'b']
I am trying to make a list of dictionaries for both 'a' and 'b' for their respective values i.e the final product will resemble
new_dict = ['a':['4', '1', '7'], 'b':['5', '8', '4']]
any help will be appreciated
Using collections
Demo:
import collections
d = collections.defaultdict(list)
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'}, {'a': '1', 'b': '8', 'c': '1', 'd': '2'}, {'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
for i in my_dict:
for k,v in i.items():
d[k].append(v)
print( d )
Output:
defaultdict(<type 'list'>, {'a': ['4', '1', '7'], 'c': ['1', '1', '1'], 'b': ['5', '8', '4'], 'd': ['3', '2', '5']})
I have a workable solution that returns a set:
>>> a = {'a': {'1', '2', '3'}, 'b': {'4', '5', '6'}, 'c': {'7', '8', '9'}}
>>> def flatten_nested(a):
temp = set(
[value for value_set in a.values() for value in value_set]
)
return temp | a.keys()
>>> flatten_nested(a)
>>> {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'}
I wondered if there was some itertools.chain-like function already built in to Python to do something similar?
I guess more simple is this:
>>> set.union(set(a), *a.values())
{'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'}
Or, here's the same thing via the bound method:
>>> set(a).union(*a.values())
{'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'}
If the values are already sets then wims answer is the simplest, but to work for iterables like a list, tuples etc.. you would have to map to a set i.e set(a).union(map(set, a.values()) or you could union the chain of all the values with the view of the keys:
from itertools import chain
def flatten_nested(a):
return a.keys() | chain(*a.values()) # a.viewkeys() python2
I have a list derived from a text file (filename) with an header
mylist = [l.split() for l in open(filename, "r")]
mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
i wish to create a dictionary directly reading the file in order to save lines of code as:
mtlist_dist = {A: ['1','10','100'], B: [''2,'20','200'], C: ['3','30','300'], D: ['4','40','400']}
You can do this easily with zip and a dictionary comprehension:
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x[0]:x[1:] for x in zip(*mylist)}
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')}
>>> {x[0]:list(x[1:]) for x in zip(*mylist)}
{'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200'], 'D': ['4', '40', '400']}
>>>
In Python 3.x, the solution becomes even more concise with extended iterable unpacking:
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x:y for x,*y in zip(*mylist)}
{'D': ['4', '40', '400'], 'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200']}
>>>
You can do it as:
my_dict = dict(zip(mylist[0], zip(*mylist[1:])))
>>> print my_dict
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')