How to dict(zip) for every item on list? - python

Here is the code:
kws = [1, 2, 3]
ab = dict(zip(['keyword:'], kws))
print ab
But it only returns: {'keyword:': 1}
I want to make it return: {'keyword:': 1, 'keyword:': 2, 'keyword:': 3}

Vignesh Kalai's comment is correct, but if you just want tuples, try:
ab = zip((['keyword'] * len(kws)), kws)

python dictionaries don't support multiple keys which is what you are trying to do, but you can have a key mapped to a list. So you could have
{keyword: [1, 2, 3]}
just by doing
kws = [1,2,3]
ab = {}
ab['Keyword'] = kws
print ab
{'Keyword': [1, 2, 3]}

Dictionary can't have same key.
Sorry, it's principle of dictionary. You question is requiring a invalid result.
I know everyone doesn't like your question.
I recommend you make list-tuple object to keep your data structure. Let's try to change the method.
print [('keyword', kw) for kw in kws]
# [('keyword', 1), ('keyword', 2), ('keyword', 3)]
So, it can simulate key-value pair. I think it can satisfy your needed.

Related

how to get all the values in a dictionary with the same key? [duplicate]

I want to add multiple values to a specific key in a python dictionary. How can I do that?
a = {}
a["abc"] = 1
a["abc"] = 2
This will replace the value of a["abc"] from 1 to 2.
What I want instead is for a["abc"] to have multiple values (both 1 and 2).
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault is that it initializes the value for that key if that key is not defined. Now, noting that setdefault returns the value, you can combine these into a single line:
a.setdefault("somekey", []).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
Append list elements
If the dict values need to be extended by another list, extend() method of lists may be useful.
a = {}
a.setdefault('abc', []).append(1) # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3]) # a is now {'abc': [1, 2, 3]}
This can be especially useful in a loop where values need to be appended or extended depending on datatype.
a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
if isinstance(v, list):
a.setdefault(some_key, []).extend(v)
else:
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
Append list elements without duplicates
If there's a dictionary such as a = {'abc': [1, 2, 3]} and it needs to be extended by [2, 4] without duplicates, checking for duplicates (via in operator) should do the trick. The magic of get() method is that a default value can be set (in this case empty set ([])) in case a key doesn't exist in a, so that the membership test doesn't error out.
a = {some_key: [1, 2, 3]}
for v in [2, 4]:
if v not in a.get(some_key, []):
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}

Extending a dictionary by adding to tupled value

(I'm just using things to represent the format my dictionary is like, this is not how it actually looks)
The current dictionary I have is in the format of :
dict={"a":(1,2,3),"b":(2,3,4),"c":(3,4,5)}
dict2={1:(1,1,2),2:(2,2,3),3:(3,3,4)}
I am trying to add on to it. I have a function that calculated an average and now I want to create a second function that would pull that average from the first function and add it to the tuple in the values of my dictionary. So if the average was 4 for "a", then I would want to add it on for it to look like this {"a":(1,2,3,4)} etc.
def func1(dict, dict2, number):
if number in dict:
for num in dict.values():
#return sum after iteration of sum through num[0] to num[2]
def func 2 (dict1, dict2)
if number in dict:
new_val_to_add= func1(dict, dict2, number)
From here I'm not sure where I would go with adding the returned value to the tuple and be able to print back dict with the added value. I was thinking of maybe converting the tuple in the first dictionary into a list and then append to that as I iterate through each key in the dictionary, and finally convert it back into a tuple. Would this be the right way of going about this?
If you want the values to be mutable, why don't you use lists instead of tuples?
You can combine two tuples using +, though:
>>> (1, 2, 3) + (4,)
(1, 2, 3, 4)
I'm having trouble following your example code, but with a dictionary following your description you can do it like this:
>>> d1 = {'a': (1, 2, 3)}
>>> d1['a'] += (4,)
>>> d1
{'a': (1, 2, 3, 4)}
Or, using a list instead:
>>> d1 = {'a': [1, 2, 3]}
>>> d1['a'].append(4)
>>> d1
{'a': [1, 2, 3, 4]}

Get a dict whose keys are combinations of a given dict without duplicate values

I have a dict like this:
dic = {'01':[1,2], '02':[1], '03':[2,3]}
what I want to achieve is a new dict, its keys are combinations of the keys (group in 2 only), and without duplicate values.
in this simple example, the output will be:
newDic = {'0102':[1,2], '0103':[1,2,3],'0203':[1,2,3]}
thanks a bunch!!
You can use a itertools.combinations to get the different combo's of keys. and then use set to get unique values of the list. Put it all into a dictionary-comprehension like this:
>>> dic = {'01':[1,2], '02':[1], '03':[2,3]}
>>> import itertools as IT
>>> {a+b: list(set(dic[a]+dic[b])) for a,b in IT.combinations(dic, 2)}
{'0203': [1, 2, 3], '0301': [1, 2, 3], '0201': [1, 2]}
You can also use join and sorted to have the keys the way you want them:
>>> {''.join(sorted([a,b])): list(set(dic[a]+dic[b])) for a,b in IT.combinations(dic, 2)}
{'0203': [1, 2, 3], '0103': [1, 2, 3], '0102': [1, 2]}
newDic = { a+b : list(set(dic[a] + dic[b])) for a in dic for b in dic if b>a }

Obtaining length of list as a value in dictionary in Python 2.7

I have two lists and dictionary as follows:
>>> var1=[1,2,3,4]
>>> var2=[5,6,7]
>>> dict={1:var1,2:var2}
I want to find the size of the mutable element from my dictionary i.e. the length of the value for a key.
After looking up the help('dict'), I could only find the function to return number of keys i.e. dict.__len__().
I tried the Java method(hoping that it could work) i.e. len(dict.items()[0]) but it evaluated to 2.
I intend to find this:
Length of value for first key: 4
Length of value for second key: 3
when the lists are a part of the dictionary and not as individual lists in case their length is len(list).
Any suggestions will be of great help.
dict.items() is a list containing all key/value-tuples of the dictionary, e.g.:
[(1, [1,2,3,4]), (2, [5,6,7])]
So if you write len(dict.items()[0]), then you ask for the length of the first tuple of that items-list. Since the tuples of dictionaries are always 2-tuples (pairs), you get the length 2. If you want the length of a value for a given key, then write:
len(dict[key])
Aso: Try not to use the names of standard types (like str, dict, set etc.) as variable names. Python does not complain, but it hides the type names and may result in unexpected behaviour.
You can do this using a dict comprehension, for example:
>>> var1 = [1,2,3,4]
>>> var2 = [5,6,7]
>>> d = {1:var1, 2:var2}
>>> lengths = {key:len(value) for key,value in d.iteritems()}
>>> lengths
{1: 4, 2: 3}
Your "Java" method would also nearly have worked, by the way (but is rather unpythonic). You just used the wrong index:
>>> d.items()
[(1, [1, 2, 3, 4]), (2, [5, 6, 7])]
>>> d.items()[0]
(1, [1, 2, 3, 4])
>>> len(d.items()[0][1])
4
>>>for k,v in dict.iteritems():
k,len(v)
ans:-
(1, 4)
(2, 3)
or
>>>var1=[1,2,3,4]
>>>var2=[5,6,7]
>>>dict={1:var1,2:var2}
ans:-
>>>[len(v) for k,v in dict.iteritems()]
[4, 3]

Saving dictionary whose keys are tuples with json, python

I am writing a little program in python and I am using a dictionary whose (like the title says) keys and values are tuples. I am trying to use json as follows
import json
data = {(1,2,3):(a,b,c),(2,6,3):(6,3,2)}
print json.dumps(data)
Problem is I keep getting TypeError: keys must be a string.
How can I go about doing it? I tried looking at the python documentation but didn't see any clear solution. Thanks!
You'll need to convert your tuples to strings first:
json.dumps({str(k): v for k, v in data.iteritems()})
Of course, you'll end up with strings instead of tuples for keys:
'{"(1, 2, 3)": ["a", "b", "c"], "(2, 6, 3)": [6, 3, 2]}'
If you want to load your data later on you have to postprocess it anyway. Therefore I'd just dump data.items():
>>> import json
>>> a, b, c = "abc"
>>> data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
>>> on_disk = json.dumps(data.items())
>>> on_disk
'[[[2, 6, 3], [6, 3, 2]], [[1, 2, 3], ["a", "b", "c"]]]'
>>> data_restored = dict(map(tuple, kv) for kv in json.loads(on_disk))
>>> data_restored
{(2, 6, 3): (6, 3, 2), (1, 2, 3): (u'a', u'b', u'c')}
You can use ujson module. ujson.dumps() accepts tuples as keys in a dictionary.
You can install ujson by pip.
For Python 3* users:
in addition to #Martijn Pieters answer,
dictonary.iteritems() is not valid, replace it with dictionary.items() :
json.dumps({str(k): v for k, v in data.items()})

Categories