Appending values to dictionary python

How to add list elements into dictionary

Let’s say I have dict = <'a': 1, 'b': 2'>and I also have a list = [‘a’, ‘b, ‘c’, ‘d’, ‘e’]. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:

2 a 3 b 1 c 1 d 1 e Total number of items: 8 
1 a 2 b 1 c 1 d 1 e Total number of items: 6 
def addToInventory(inventory, addedItems) for items in list(): dict.setdefault(item, []) def displayInventory(inventory): print('Inventory:') item_count = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_count += int(v) print('Total number of items: ' + str(item_count)) newInventory=addToInventory(dict, list) displayInventory(dict) 

@TimCastelijns — that was the issue. it didn’t add ‘a’ or ‘b’ from the list and kept the original value from dict.

@thefourtheye — there was a .append() at the end of that but it was giving an error about int not having a method .append so I took it out. still learning!

12 Answers 12

You just have to iterate the list and increment the count against the key if it is already there, otherwise set it to 1.

>>> d = >>> l = ['a', 'b', 'c', 'd', 'e'] >>> for item in l: . if item in d: . d[item] += 1 . else: . d[item] = 1 >>> d

You can write the same, succinctly, with dict.get , like this

>>> d = >>> l = ['a', 'b', 'c', 'd', 'e'] >>> for item in l: . d[item] = d.get(item, 0) + 1 >>> d

dict.get function will look for the key, if it is found it will return the value, otherwise it will return the value you pass in the second parameter. If the item is already a part of the dictionary, then the number against it will be returned and we add 1 to it and store it back in against the same item . If it is not found, we will get 0 (the second parameter) and we add 1 to it and store it against item .

Now, to get the total count, you can just add up all the values in the dictionary with sum function, like this

The dict.values function will return a view of all the values in the dictionary. In our case it will numbers and we just add all of them with sum function.

Читайте также:  Python получить часть строки до символа

Use collections module:

>>> import collections >>> a = >>> b = ["a", "b", "a", "1"] >>> c = collections.Counter(b) + collections.Counter(a) >>> c Counter() >>> sum(c.values()) 14 

If you are looking for a solution for the List to Dictionary Function for Fantasy Game Inventory in Automating boring stuff with Python, here is a code that works:

# inventory.py stuff = #this part of the code displays your current inventory def displayInventory(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print("Total number of items: " + str(item_total)) #this launches the function that displays your inventory displayInventory(stuff) dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # this part is the function that adds the loot to the inventory def addToInventory (inventory, addedItems): print('Your inventory now has:') #Does the dict has the item? If yes, add plus one, the default being 0 for item in addedItems: stuff[item] = stuff.get(item, 0) + 1 # calls the function to add the loot addToInventory(stuff, dragonLoot) # calls the function that shows your new inventory displayInventory(stuff) 

While looking for a solution for this precise exercise, this was the first result in google, hence why I posted here with the solution that the book precisely calls for. I had to learn from the other answers and adapt it a bit.

The question on ‘List to Dictionary Function for Fantasy Game Inventory’ — Chapter 5. Automate the Boring Stuff with Python.

# This is an illustration of the dictionaries # This statement is just an example inventory in the form of a dictionary inv = # This statement is an example of a loot in the form of a list dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # This function will add each item of the list into the dictionary def add_to_inventory(inventory, dragon_loot): for loot in dragon_loot: inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0 inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1 return inventory # This function will display the dictionary in the prescribed format def display_inventory(inventory): print('Inventory:') total_items = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) total_items = total_items + 1 print('Total number of items: ' + str(total_items)) # This function call is to add the items in the loot to the inventory inv = add_to_inventory(inv, dragon_loot) # This function call will display the modified dictionary in the prescribed format display_inventory(inv) 

Источник

Читайте также:  METANIT.COM

Appending values to a dictionary in Python

I’m looking at the smartest way of using a dictionary to handle some data output. I have a unique key which will have associated it other values so for example we have 1:[2, 3, 4, 7], 2:[8, 9, 5]. What I’d like to do is to be able to append the values such that the for the first key I could add the number 13 and get the following:

dict[master = dict[master].append(id) 

but I get the following: AttributeError: ‘int’ object has no attribute ‘append’ Now I could simply take the previous values of they key and simply do the following (id = 17):

I could use some stripping functions — but is there a good easy way and simple way of doing this. I might be overlooking something simple here. Thanks in advance.

3 Answers 3

Use a collections.defaultdict (and, wottthehell, make each entry a collections.deque just for fun; you could also use a plain old list of course).

from collections import defaultdict, deque d = defaultdict(deque) # or . (list) d[1].append(2) d[1].extend([3, 4, 7, 13]) 

The basic idea here is that your dictionary values are always deque s and you always append to them, so you never have to worry about whether a value is an int . If you use a key that doesn’t exist in the dictionary, defaultdict will create a new deque for you automatically, so you never have to check whether the key already exists in the dictionary either.

If you already have a regular dictionary with single int values — say it was a return value for some function you called — you can just use that dict to build up your new one, before using it for whatever you’re doing with it.

d = defaultdict(deque) for key, value in old_d.iteritems(): dAppending values to dictionary python.append(value) 

Источник

How to add key,value pair to dictionary? [duplicate]

Thanks it’s working..I meant resultset of query. Do you know which are the concerns using python..i don’t know am new of this technology before i have worked in dotnet.

Читайте также:  Date validations in java

@Krishnasamy: If you have earlier worked on dotnet, Python will be a pleasure to work with. It is as versatile as dotnet and java, if not more

For quick reference, all the following methods will add a new key ‘a’ if it does not exist already or it will update the existing key value pair with the new value offered:

data['a']=1 data.update() data.update(dict(a=1)) data.update(a=1) 

You can also mixing them up, for example, if key ‘c’ is in data but ‘d’ is not, the following method will updates ‘c’ and adds ‘d’

Why is the down vote? The answer is trying to add useful info so viewers can have an alternative answer which IMHO is more comprehensive, could the gentleman/women who down voted pls clarify?

You don’t need to answer this question since its a duplicate — the appropriate way of handling it is by flagging it as a dupe — see more info there How should duplicate questions be handled?

SO really needs to figure out a way to make things surface better. This is down voted for being a duplicate. But it’s the first thing that appears when a user searches. The down vote then starts more conversation, which causes this answer to FURTHER rise in popularity, thereby hiding the original answer. I would have never have found the original answer had this one not existed. So why not just delete this qeustion completely?

I am not sure what you mean by «dynamic». If you mean adding items to a dictionary at runtime, it is as easy as dictionaryAppending values to dictionary python = value .

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

I got here looking for a way to add a key/value pair(s) as a group — in my case it was the output of a function call, so adding the pair using dictionaryAppending values to dictionary python = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.

Источник

Оцените статью