Creating a union of two dictionaries - python

What I am attempting to accomplish is to create a union of two dictionaries (consisting of single integers i.e. 1, 2, 3, 4, etc.) by taking the keys out of the dictionary, putting them into two lists, joining the two lists and then putting them back into a new dictionary that contains both lists. However, I am running into the
TypeError: unsupported operand type(s) for +:
'builtin_function_or_method' and 'builtin_function_or_method'
How would I get around this error?
Here are the relevant pieces of code.
class DictSet:
def __init__(self, elements):
self.newDict = {}
for i in elements:
self.newDict[i] = True
def union(self, otherset):
a = self.newDict.keys
b = otherset.newDict.keys
list1 = a + b
new = DictSet(list1)
return new
def main():
allints = DictSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
odds = DictSet([1, 3, 5, 7, 9])
evens = DictSet([2, 4, 6, 8, 10])

Why not use dict.update()?
def union(self, otherset):
res = DictSet([])
res.newDict = dict(self.newDict)
res.newDict.update(otherset.newDict)
return res

You must call the keys() method. Try this:
a = self.newDict.keys()
b = otherset.newDict.keys()
EDIT: I see you are using Python3. In that case:
a = list(self.newDict)
b = list(otherset.newDict)

Related

Adding elements of a list into a dictionary using .get() method

I have a list of elements [1, 2, 5, 2, 3, 7, 5, 8]. I want to put it into a dictionary so it would go "key : how many times it appears in the list", so the dictionary looks something like as follows:
{"1:1", "2:2", "5:2", "3:1", "7:1", "8:1"}
The solution should be applicable to any list.
I did the iteration of the list, but am receiving an error when it comes to adding the elements into the dictionary.
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0)
print(midwayDict)
All it gives me is " AttributeError: 'int' object has no attribute 'get' ".
Is something wrong with the method I'm using? or should I use a different way?
I saw this being used somewhere a while ago, but I am not being able to find where of how exactly to do this.
The error in your code is
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0) # <- you are assigning 0 to dict so in next iteration you are accessing .get method on integer so its saying there is no get method on int object
print(midwayDict)
Should be
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
_ = midwayDict.setdefault(element, 0)
midwayDict[element] += 1
print(midwayDict)
Better is
from collections import Counter
given = (1, 2, 5, 2, 3, 7, 5, 8)
print(Counter(given))
There is only one error in your code.
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in set(given):
midwayDict[element] = midwayDict.get(element, 0)+1 # edited
print(midwayDict)
The better way to do this is by using dictionary comprehension.
given = (1, 2, 5, 2, 3, 7, 5, 8)
d = {a:given.count(a) for a in set(given)}
print(d)

How to fix TypeError: 'NoneType' object is not iterable in Python?

How can I resolve this problem?
def common_elements(tuple1, tuple2):
set1 = set(tuple1)
set2 = set(tuple2)
lst1 = list(set1.intersection(set2))
return tuple(lst1.sort()) #TypeError: 'NoneType' object is not iterable
print(common_elements((1, 2, 3, 4), (4, 53, 3, 5, 2, 5, 2, 6, 0)))
list.sort() will sort the list in-place, but the return value is None.
sorted(list) will return a new list object that is sorted.
The correct code should thus be:
def common_elements(tuple1, tuple2):
set1 = set(tuple1)
set2 = set(tuple2)
lst1 = list(set1.intersection(set2))
return tuple(sorted(lst1))
print(common_elements((1, 2, 3, 4), (4, 53, 3, 5, 2, 5, 2, 6, 0)))
sort() sorts a list in place and returns None. You need to call sort() and then return the same list in two different statements:
lst1.sort()
return tuple(lst1)

Appending elements to a list based on condition

I was trying to append few elements to a list list_accepted_outsidenestant. When i try to print the list list_accepted_outsidenestant, i get: list_accepted_outsidenestant- [([971, 977, 728, 740], set([728, 977, 971, 740]))]. The list is showing a list and set with same elements. Can anyone pointout the mistake i am doing? Because of this, i am getting an error:
set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant
TypeError: unhashable type: 'list'
I have shown part of code only relevant to the current question.
def leo(tag_data):
available_ants_outside = []
ori = []
for id, (x, y) in tag_data:
available_ants_outside.append(id)
if for_coordinates_outside_nest((x, y)) is True:
ori.append(id)
return ori
def virgo(tag_data):
available_ants_inside = []
list_insidenest_ant_id = []
set_inside_nest_ant_id = set()
for id, (x, y) in tag_data:
available_ants_inside.append(id)
if for_coordinates_inside_nest((x, y)) is True:
list_insidenest_ant_id.append(id)
set_inside_nest_ant_id = set(list_insidenest_ant_id)
return list_insidenest_ant_id,set_inside_nest_ant_id
def bambino(ori,list_insidenest_ant_id):
list_accepted_outsidenestant = []
set_accepted_outsidenest_antlist = set()
set_accepted_insidenest_antlist = set()
if len(list_accepted_outsidenestant) < num_accepted:
if (len(ori) > 0) or (len(list_insidenest_ant_id) >0):
list_accepted_outsidenestant.extend(ori[0:min(len(ori),
num_accepted-len(list_accepted_outsidenestant))])
set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant)
print "list_accepted_outsidenestant-" + str(list_accepted_outsidenestant)
set_accepted_insidenest_antlist = set(list_insidenest_ant_id)
return set_accepted_outsidenest_antlist,set_list_outsideant_id,set_accepted_insidenest_antlist
The problem is that you're appending a list to a list.
You can either iterate over the list you want to add:
items_to_add = ori[0:min(len(ori),
num_accepted-len(list_accepted_outsidenestant))]
for item in items_to_add:
list_accepted_outsidenestant.append(item)
Or add the lists:
list_accepted_outsidenestant = list_accepted_outsidenestant + ori[0:min(len(ori), num_accepted-len(list_accepted_outsidenestant))]
Or as bruno pointed out (even better), extend the list.
list_accepted_outsidenestant.extend(ori[0:min(len(ori), num_accepted-len(list_accepted_outsidenestant))])
append function add whole into other array
extend function extend add array into previous array
In [1]: a = [1,2,3,4]
In [2]: b = [10,9,8,7,6]
In [3]: a.append(b)
In [4]: a
Out[4]: [1, 2, 3, 4, [10, 9, 8, 7, 6]]
In [5]: c = [1,2,3,4]
In [6]: c.extend(b)
In [7]: c
Out[7]: [1, 2, 3, 4, 10, 9, 8, 7, 6]
Hope this code help you

using += to populate a list through while loop gives me an error

I have a very basic understanding that += and .append are quite similar in terms of appending new element to a list. However, I find them perform differently when I try to populate a list with random integer values through while loop. append works well, however, running my program with += will give me an error :
TypeError: 'int' object is not iterable
Here is my code:
1.use +=
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0,10)
i = i + 1
print random_list
**TypeError: 'int' object is not iterable**
2.use .append
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list.append(random.randint(0,10))
i = i + 1
print random_list
**[4, 7, 0, 6, 3, 0, 1, 8, 5, 10, 9, 3, 4, 6, 1, 1, 4, 0, 10, 8]**
Does anyone know why would this happen?
This happens because += is for appending a list to the end of another list, not for appending an item.
It is the short version of doing:
items = items + new_value
If new_value isn't a list this will fail because you can't use + to add a item to a list.
items = items + 5 # Error: can only add two list together
The solution is to make the value into a one-item long list:
items += [value]
Or to use .append - the preferred way to add single items to a list.
Yes, it's tricky. just add a , at end of random.randint(0, 10)
import random
random_list = []
list_length = 20
# Write code here and use a while loop to populate this list of random integers.
i = 0
while i < 20:
random_list += random.randint(0, 10),
i += 1
print random_list
It will print:
[4, 7, 7, 10, 0, 5, 10, 2, 6, 2, 6, 0, 2, 7, 5, 8, 9, 8, 0, 2]
You can find more explanation about trailing ,

Working with lists and slicing

This seems like an easy task and I honestly don't know what the problem is. I have a list such as [0,1,2,3,4,5,6] and such and I need to pick and index, lets say 3, and the output should look like [4,5,6,3,0,1,2] and here is my code
def cut_list(listA, index):
return listA[index+1:] + listA[index] + listA[0:index]
Yet the listA[index] function isn't working properly and giving an error, however if I take out the other parts and only do "return listA[index]" it will output 3
listA[index] is a scalar value which can't be concatenated with a list. You're doing something akin to:
>>> 3 + []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Lists can only be concatenated with other lists, so the solution is to simply change listA[index] into a list with that as the only element. e.g. [listA[index]]:
def cut_list(listA, index):
return listA[index+1:] + [listA[index]] + listA[0:index]
To make it work for most sequence types, we can do a little clever slicing:
def cut_list(listA, index):
return listA[index+1:] + listA[index:index+1] + listA[0:index]
This works because the slice x[idx:idx+1] should return a sequence of the same type as x that has only the idx'th element from x.
>>> cut_list(range(10), 3)
[4, 5, 6, 7, 8, 9, 3, 0, 1, 2]
>>> cut_list('foo3bar', 3)
'bar3foo'
>>> cut_list(tuple(range(10)), 3)
(4, 5, 6, 7, 8, 9, 3, 0, 1, 2)

Categories