What is the cleanest way to update the values of multiple keys in a dictionary to the values stored in a tuple?
Example:
I want to go from
>>>mydict = {'a':None, 'b':None, 'c':None, 'd':None}
>>>mytuple = ('alpha', 'beta', 'delta')
to
>>>print mydict
{'a':'alpha', 'b':'beta', 'c':None, 'd':'delta'}
Is there an easy one-liner for this? Something like this seems to be getting close to what I want.
EDIT:
I don't wish to assign values to keys based on their first letter. I'm just hoping for something like
mydict('a','b','d') = mytuple
Obviously that doesn't work, but I'm hoping for something similar to that.
If you're trying to create a new dictionary:
d = dict(zip(keys, valuetuple))
If you're trying to add to an existing one, just change the = to .update(…).
So, your example can be written as:
mydict.update(dict(zip('abd', mytuple))))
If you're doing this more than once, I'd wrap it up in a function, so you can write:
setitems(d, ('a', 'b', 'd'), mytuple)
Or maybe a "curried" function that parallels operator.itemgetter?
You could use list comprehension to make it a one-liner, though it's not super efficient.
keys = [ 'a', 'b', 'c', 'd']
values = ['alpha', 'beta', 'delta']
dictionary = dict([(k,v) for k in keys for v in values if v.startswith(k)])
print dictionary #prints {'a': 'alpha', 'b': 'beta', 'd': 'delta'}
Assuming the association key <-> value is the first letter of the value is the first letter of the key.
dict( (v[0],v) for v in mytuple if v[0] in mydict)
I would avoid one-liners in this case. It makes code more readable.
for t in mytuple:
if t[0] in mydict.keys():
mydict[t[0]] = t
If you want to add mytuple items even if the key does not exist, simply remove the if statement.
Related
For example, my dictionary contain this:
a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
To sort key on that list, I can do this:
b = []
for m in a:
b.append(m)
b.sort()
for value in b:
print(a[value])
The problem is: 'd' and 'e' share the same value 4, and its only export one value. But I want to export all of them. How can I do that?
A dictionary is assigns a value to a key (or a key references a specific value). Therefore it is not possible to have a dictionary with the same key twice (check, what a looks like after assigning!).
What you may want to look at is a list of tuples!
a = [(1,'a'),(3,'b'),(2,'c'),(4,'d'),(1,'e'),(4,'f')]
After that, you can do the sorting just by doing this:
a.sort(key=lambda x: x[0])
Duplicate keys in a dictionary is not allowed. Your dict does not contain what you think.
>>> a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
>>> a
{1: 'e', 2: 'c', 3: 'b', 4: 'f'}
When initializing your dictionary, the key 4 is defined twice: 4:'d', 4:'f'.
The second value 'f' overwrites the 'd' stored at a[4]. This is by design and therefore, you would need to correct your implementation to take this behaviour into account.
Hello I am trying to find the values in a dictionary using they keys which is a 2 element tuple.
For example any basic dictionary would look like this:
dict = {'dd':1, 'qq':2, 'rr':3}
So if I would like to find the value of 'dd' I would simply do:
>>>dict['dd']
1
but what if I had a dictionary who's keys were 2 element tuples:
dict = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
Then how can I find the value of 'dd' or 'rr'
You aren't using the dictionary properly. The keys in the dictionary should be in the form that you want to look them up. So unless you are looking up values by tuple ('dd', 'ee') you should separate out those keys.
If you are forced to start with that dict structure then you can transform into the desired dict using this:
d1 = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
# creates {'dd': 1, 'ee': 1, 'qq': 2, 'bb': 2, 'rr': 3, 'nn': 3}
d2 = {x:v for k, v in d1.items() for x in k}
You need to revert to a linear search
>>> D = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
>>> next(D[k] for k in D if 'dd' in k)
1
If you need to do more than one lookup, it's worth building a helper dict as #bcorso suggests
having said that. dict is probably the wrong datastructure for whatever problem you are trying to solve
Use a list comprehension:
>>> d={('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3, ('kk','rr'):4}
>>> [(t,d[t]) for t in d if 'rr' in t]
[(('kk', 'rr'), 4), (('rr', 'nn'), 3)]
I have a dictionary say..
dict = {
'a' : 'b',
'c' : 'd'
}
In php I would to something like implode ( ',', $dict ) and get the output 'a,b,c,d'
How do I do that in python?
This seems to be easiest way:
>>> from itertools import chain
>>> a = dict(a='b', c='d')
>>> ','.join(chain(*a.items()))
'a,b,c,d'
First, the wrong answer:
','.join('%s,%s' % i for i in D.iteritems())
This answer is wrong because, while associative arrays in PHP do have a given order, dictionaries in Python don't. The way to compensate for that is to either use an ordered mapping type (such as OrderedDict), or to force an explicit order:
','.join('%s,%s' % (k, D[k]) for k in ('a', 'c'))
Use string join on a flattened list of dictionary items like this:
",".join(i for p in dict.items() for i in p)
Also, you probably want to use OrderedDict.
This has quadratic performance, but if the dictionary is always small, that may not matter to you
>>> sum({'a':'b','c':'d'}.items(), ())
('a', 'b', 'c', 'd')
note that the dict.items() does not preserve the order, so ('c', 'd', 'a', 'b') would also be a possible output
a=[]
[ a.extend([i,j]) for i,j in dict.items() ]
Either
[value for pair in {"a": "b", "c" : "d"}.iteritems() for value in pair]
or
(lambda mydict: [value for pair in mydict.iteritems() for value in pair])({"a": "b", "c" : "d"})
Explanation:
Simplified this example is return each value from each pair in the mydict
Edit: Also put a ",".join() around these. I didn't read your question properly
I know this is an old question but it is also good to note.
The original question is misleading. implode() does not flatten an associative array in PHP, it joins the values
echo implode(",", array("a" => "b", "c" => "d"))
// outputs b,d
implode() would be the same as
",".join(dict.values())
# outputs b,d
This is not very elegant, but works:
result=list()
for ind in g:
result.append(ind)
for cval in g[ind]:
result.append(cval)
dictList = dict.items()
This will return a list of all the items.
Searching for elements in a python list and then accessing particular values
Mylist = [('A',3,['x','y','z']),('B',2,['m','n'])]
Variable = 'A'
i = Mylist.index(Variable)
print i
For example I would like to check if is Variable is present and access its elements like
is present then access each of sublist elements one by one
For instance in the above example I would like to check if 'A' is present and if yes then
get access to its individual sublist elements like 'x' , 'y' and 'z'
It looks like you haven't found the Python dict yet. Perhaps you mean:
mydict = {}
mydict['A'] = {'count': 3, 'letters': ['x','y','z']}
mydict['B'] = {'count': 2, 'letters': ['m','n']}
mydict is a dictionary that itself contains dictionaries.
You can then look them up with:
val = mydict['A']
print val['letters']
Of course, there's little point in storing 'count' since you can just use len() if you need to. You could do it like so:
mydict = {'A': ['x','y','z'], 'B': ['m','n']}
print mydict['A']
You just need to use a dictionary...
myDict = dict([('A',3,['x','y','z']),('B',2,['m','n'])])
if 'A' in myDict:
val = myDict['A']
As others have said, a dict is really the appropriate data type to use when you need to index things by arbitrary data types (like strings). With nested sequences, there's no guarantee that your 'index' (the 'A' and 'B' in this case) will be unique, and some extra contortion is needed to look up values. Also as others have said, the ['x', 'y', 'z'] part will remain in order, regardless of whether it's a list-in-a-tuple-in-a-list, or a list-in-a-dict.
That said, the easiest way I can think of to find the tuple you want without using a dict is:
indices = zip(*Mylist)[0] # ('A', 'B')
index = indices.index('A') # 0
result = Mylist[index] # ('A', 3, ['x', 'y', 'z'])
To get at the sublist, use its index:
sublist = result[2]
or unpack it:
lookup, length, sublist = result
Mylist = [('A',3,['x','y','z']),('B',2,['m','n']),
('C',5,['r','p','u']),('A',10,['k','X']),
('E',8,['f','g','h','j'])]
for i,(a,b,c) in enumerate(Mylist):
if a=='A':
print i,c
result
0 ['x', 'y', 'z']
3 ['k', 'X']
This question already has answers here:
How can I convert a dictionary into a list of tuples?
(13 answers)
Closed 3 years ago.
I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.
#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"
#lists
temp = []
dictList = []
#My attempt:
for key, value in dict.iteritems():
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
aKey = ""
aValue = ""
That's my attempt at it... but I can't work out what's wrong?
dict.items()
Does the trick.
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.
To fix your code, try something like:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.
Or just use dict.items() as has been suggested.
You should use dict.items().
Here is a one liner solution for your problem:
[(k,v) for k,v in dict.items()]
and result:
[('Food', 'Fish&Chips'), ('2012', 'Olympics'), ('Capital', 'London')]
or you can do
l=[]
[l.extend([k,v]) for k,v in dict.items()]
for:
['Food', 'Fish&Chips', '2012', 'Olympics', 'Capital', 'London']
>>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
>>> list(reduce(lambda x, y: x + y, a.items()))
['foo', 'bar', 'baz', 'quux', 'hello', 'world']
To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.
Probably you just want this:
dictList = dict.items()
Your approach has two problems. For one you use key and value in quotes, which are strings with the letters "key" and "value", not related to the variables of that names. Also you keep adding elements to the "temporary" list and never get rid of old elements that are already in it from previous iterations. Make sure you have a new and empty temp list in each iteration and use the key and value variables:
for key, value in dict.iteritems():
temp = []
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
Also note that this could be written shorter without the temporary variables (and in Python 3 with items() instead of iteritems()):
for key, value in dict.items():
dictList.append([key, value])
If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()
Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:
headers = ['Capital', 'Food', 'Year']
countries = [
['London', 'Fish & Chips', '2012'],
['Beijing', 'Noodles', '2008'],
]
for olympics in countries:
print zip(headers, olympics)
gives
[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]
Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.