I am using an existing dictionary:
my_dict = {a: [(1,2,3), (4,5,6)]}
*example
and I have defying a func that gets a new keys and values to my_dict:
def adding_new():
my_dict[new_key] = [(7,8,9)]
i need the dict to update and be saved in my program, but it keeps staying the same as started.
any suggestions?
edit:
Actually I get why you answer that, im pretty sure im not asking my question right.. im new at python and english isnt my spoken language
What im asking is why when i call my function, I dont see any changes in my code? I mean, is there any way to make my program to make changes in my existing code?
It's a bit difficult to tell from your code..
But I think your main problem is that you are just defining a function and not calling the function.
First I fixed the syntax of your code:
my_dict = {"a": (1,2,3), "b": (4,5,6)}
def adding_new():
my_dict["new_key"] = (7,8,9)
Secondly I add a call of the fuction you defined:
my_dict = {"a": (1,2,3), "b": (4,5,6)}
def adding_new():
my_dict["new_key"] = (7,8,9)
adding_new()
Related
In Python3.X, when passing methods into Map/Filter/Reduce, why is it done without '()'? Does this apply to all generators?
This is probably a simple question but I can't find a clear answer in docs. I'm hoping to understand the reasons rather than just "memorizing" syntax.
e.g.
map(str.upper, ['a', 'b', 'c']) #this works
vs
map(str.upper(), ['a', 'b', 'c']) #this gives an error
This is confusing at first, especially when you come from other programming languages. In Python the functions are objects and you can pass them along without invoking them. Check below example:
def func(): # function definition
print("func was invoked")
a = func # assign func object (without invoking it)
print(a, type(a))
a() # invoking the function
map will use this function object to invoke the function for each item in the iterable.
I know that it is possible to modify a list inside a function by using assignment as followslis[:] = new_list, however the question is, is it possible to modify a deque inside a function as it is also an iterable?
Of course without using return inside the function.
It not possible to use 'deq[:] = new_deq ' as it gives the following error: TypeError: sequence index must be integer, not 'slice'
deque does not support a slice as an index, so to achieve the effect of lis[:] = new_list with a deque, you can clear it first before extending it:
from collections import deque
def f(q, new_list):
q.clear()
q.extend(new_list)
d = deque([1, 2])
f(d, [2, 3])
print(d)
This outputs:
deque([2, 3])
I also found that it is possible to do it this way :
def f(q, new_list):
q.__init__(new_list)
It is working for me, however I do not know if this way has any disadvantages.
I've got an object class that is provided a dictionary at __init__(), which in turns contains nested dictionaries. What I want to do is create a shortcut to (in this case) a list that is buried several layers into the dict.
Obviously this will work:
class Example(object):
def __init__(self, foo: dict):
self.shortcut = foo['a']['b']['c']
The problem is that I would like to do this in such a way that Eclipse/PyDev knows that foo['a']['b']['c'] a list (and therefore so is self.shortcut), similar to the way that adding :dict tells PyDev that foo is a dictionary.
The closest I've come to a solution is:
self.shortcut = list( foo['a']['b']['c'] )
But that makes a copy, and I want to preserve the link to foo. I could turn around and do the assignment in reverse, by following it up with
foo['a']['b']['c'] = self.shortcut
But that... that just offends my programming sensibilities.
I am somewhat new to coding. I have been self teaching myself for the past year or so. I am trying to build a more solid foundation and am trying to create very simple programs. I created a class and am trying to add 'pets' to a dictionary that can hold multiple 'pets'. I have tried changing up the code so many different ways, but nothing is working. Here is what I have so far.
# Created class
class Animal:
# Class Attribute
classes = 'mammal'
breed = 'breed'
# Initializer/Instance Attribrutes
def __init__ (self, species, name, breed):
self.species = species
self.name = name
self.breed = breed
# To get different/multiple user input
#classmethod
def from_input(cls):
return cls(
input('Species: '),
input('Name: '),
input('Breed: ')
)
# Dictionary
pets = {}
# Function to add pet to dictionary
def createpet():
for _ in range(10):
pets.update = Animal.from_input()
if pets.name in pets:
raise ValueError('duplicate ID')
# Calling the function
createpet()
I have tried to change it to a list and use the 'append' tool and that didn't work. I am sure there is a lot wrong with this code, but I am not even sure what to do anymore. I have looked into the 'collections' module, but couldn't understand it well enough to know if that would help or not. What I am looking for is where I can run the 'createpet()' function and each time add in a new pet with the species, name, and breed. I have looked into the sqlite3 and wonder if that might be a better option. If it would be, where would I go to learn and better understand the module (aka good beginner tutorials). Any help would be appreciated. Thanks!
(First of all, you have to check for a duplicate before you add it to the dictionary.)
The way you add items to a dictionary x is
x[y] = z
This sets the value with the key y equal to z or, if there is no key with that name, creates a new key y with the value z.
Updated code:
(I defined this as a classmethod because the from_input method is one as well and from what I understand of this, this will keep things working when it comes to inheriting classes, for further information you might want to look at this)
#classmethod
def createpet(cls):
pet = cls.from_input()
if pet.name in cls.pets:
raise ValueError("duplicate ID")
else:
cls.pets[pet.name] = pet
I have some code getting data and then selecting it in order. For this I use simple maps that I may later access with ease (I thought..).
I use the following code within a loop to insert maps to another map named "companies":
def x = [:]
x.put(it.category[i], it.amount[i])
companies.put(it.company, x)
And I can surely write the result out: [Microsoft:[Food:1], Apple:[Food:1]]
But then, when I am about to get the food value of each company it always is null. This is the code I use to get the values:
def val = companies.get(it.company).get(key.toString())
def val = companies[it.company][key] // doesn't make a difference
Val is always null. Can someone help and / or explain why I have this error. What am I doing wrong? I mean, I can clearly see the 1 when I print it out..
My guess is that it.category[i] and key are completely different types...
One thing you could try is:
x.put(it.category[i].toString(), it.amount[i])
and then
def val = companies[it.company][key.toString()] // doesn't make a difference
The solution was simple to make the category as a string:
x.put(it.category[i].toString(), it.amount[i])
And after that little fix it all works as expected.