I want to create a new dict with a loop but I don't find the way to push key and value in loop with append. I try something like this but I'm still searching the good way.
frigo = {"mangue" : 2, "orange" : 8, "cassoulet" : 1, "thon" : 2, "coca" : 8, "fenouil" : 1, "lait" : 3}
new_frigo = {}
for i, (key, value) in enumerate(frigo.items()):
print(i, key, value)
new_frigo[i].append{key,value}
There's already a python function for that:
new_frigo.update(frigo)
No need for a loop! dict.update(other_dict) just goes and adds all content of the other_dict to the dict.
Anyway, if you wanted for some reason to do it with a loop,
for key, value in frigo.items():
new_frigo[key] = value
would do that. Using an i here makes no sense - a dictionary new_frigo doesn't have indices, but keys.
You can use update to append the key and values in the dictionary as follows:
frigo = {"mangue": 2, "orange": 8, "cassoulet": 1, "thon": 2, "coca": 8, "fenouil": 1, "lait": 3}
new_frigo = {}
for (key, value) in frigo.items():
new_frigo.update({key:value})
print(new_frigo)
Result:
{'mangue': 2, 'orange': 8, 'cassoulet': 1, 'thon': 2, 'coca': 8, 'fenouil': 1, 'lait': 3}
Related
I have a nested dict that looks like:
{KeyA: {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
{KeyB: {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}
I would like to output this to a csv where the desired row format is:
ItemA, 1, Item B, 2, ItemC, 3, ItemD, 4, ItemE, 5, ItemF, 6
I've managed to get a row that's keys and then another below it with the associated value with the below code:
for item in myDict:
item = myDict[x]
itemVals = item.values()
wr.writerow(item)
wr.writerow(itemVals)
x += 1
I've tried a number of ways of reformatting this and keep running into subscriptable errors every which way I try.
The length of the top level dict could be large, up to 30k nested dicts. The nested dicts are a constant length of 6 key:value pairs, currently.
What's a clean way to achieve this?
Here is an implementation with loops:
myDict = {'KeyA': {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
'KeyB': {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}}
with open("output.csv", "w") as file:
for key in myDict:
for nestedKey in myDict[key]:
file.write(key + "," + str(myDict[key][nestedKey]) + ",")
file.write("\n")
output.csv:
KeyA,1,KeyA,2,KeyA,3,KeyA,4,KeyA,5,KeyA,6,
KeyB,2,KeyB,3,KeyB,4,KeyB,5,KeyB,6,KeyB,7,
Hi all I have a dictionary and a list of key
Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7}}
L = ['Triangle','Traingle5R','Rectangle','CircularMMW','CircularHMW']
I would like to fill the dictionary with the missing key present in the list and set them at Zero, by keeping the older one with their respective value
Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7}}
L = ['Triangle','Traingle5R','Rectangle','cMMW','cHMW',"sRib"]
I am trying this code but it set all key at zero also the one that has a starting value
for el in L:
for k,v in Diz.items():
for k2,v2 in v.items():
if el not in k2:
Diz[k][el] = 0
print(Diz)
I would like to have this output
Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9,'Triangle':0,'Traingle5R':0,'Rectangle':0,'cMMW','cHMW}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7,'Triangle':0,'Traingle5R':0,'Rectangle':0,"cHMW":0}}
And at the end I would also produce a table in a txt file for each line a key and dictionary value.
You can iterate through each keys of the dictionary, and use dict.get for inner dictionary passing 0 as default value and assign it back to the inner dictionary.
for key in Diz:
for item in L:
Diz[key][item] = Diz[key].get(item, 0)
OUTPUT:
{'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9, 'Triangle': 0, 'Traingle5R': 0, 'Rectangle': 0, 'cMMW': 0}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7, 'Triangle': 0, 'Traingle5R': 0, 'Rectangle': 0, 'cHMW': 0}}
I need to replace dictionary values based on their index
Ex:
mydict = {'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 6, 'pwp': 5}
Here i need to replace the value of the key at 4th index with new value 10
Expected output:
{'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 10, 'pwp': 5}
You can use dict.keys() to get the keys of the dictionary, then find the key at the 4th index of that list and set that value in the dictionary:
mydict = {'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 6, 'pwp': 5}
keys = list(mydict.keys())
mydict[keys[4]] = 10
print(mydict)
Output:
{'abc': 10, 'iji': 9, 'sls': 8, 'eie': 2, 'wlw': 10, 'pwp': 5}
Note
This will only work in Python < 3.7 if the dictionary is not modified (entries added or deleted after creation) as otherwise mydict.keys() is not guaranteed to return the same order of result each time. For versions of Python < 3.7 it is safer to use an OrderedDict.
I have a dictionary users with 1748 elements as (showing only the first 12 elements)-
defaultdict(int,
{'470520068': 1,
'2176120173': 1,
'145087572': 3,
'23047147': 1,
'526506000': 1,
'326311693': 1,
'851106379': 4,
'161900469': 1,
'3222966471': 1,
'2562842034': 1,
'18658617': 1,
'73654065': 4,})
and another dictionary partition with 452743 elements as(showing first 42 elements)-
{'609232972': 4,
'975151075': 4,
'14247572': 4,
'2987788788': 4,
'3064695250': 2,
'54097674': 3,
'510333371': 0,
'34150587': 4,
'26170001': 0,
'1339755391': 3,
'419536996': 4,
'2558131184': 2,
'23068646': 6,
'2781517567': 3,
'701206260771905541': 4,
'754263126': 4,
'33799684': 0,
'1625984816': 4,
'4893416104': 3,
'263520530': 3,
'60625681': 4,
'470528618': 3,
'4512063372': 6,
'933683112': 3,
'402379005': 4,
'1015823005': 2,
'244673821': 0,
'3279677882': 4,
'16206240': 4,
'3243924564': 6,
'2438275574': 6,
'205941266': 3,
'330723222': 1,
'3037002897': 0,
'75454729': 0,
'3033154947': 6,
'67475302': 3,
'922914019': 6,
'2598199242': 6,
'2382444216': 3,
'1388012203': 4,
'3950452641': 5,}
The keys in users(all unique) are all in partition and also are repeated with different values(and also partition contains some extra keys which is not of our use). What I want is a new dictionary final which connects the keys of users matching with those of partition with the values of partition, i.e. if I have '145087572' as a key in users and the same key has been repeated twice or thrice in partition with different values as: {'145087572':2, '145087572':3,'145087572':7} then I should get all these three elements in the new dictionary final. Also I have to store this dictionary as a key:value RDD.
Here's what I tried:
user_key=list(users.keys())
final=[]
for x in user_key:
s={x:partition.get(x) for x in partition}
final.append(s)
After running this code my laptop stops to respond (the code still shows [*]) and I have to restart it. May I know that is there any problem with my code and a more efficient way to do this.
First dictionary cannot hold duplicate keys, duplicate key's value will be ovewritten by the last value of same key.
Now lets analyze your code
user_key=list(users.keys()) # here you get all the keys say(1,2,3)
final=[]
for x in user_key: #you are iterating over the keys so x will be 1, 2, 3
s={x:partition.get(x) for x in partition} #This is the reason for halting
''' breaking the above line this is what it looks like.
s = {}
for x in partition:
s[x] = partition.get(x)
isn't the outer forloop and inner forloop is using the same variable x
so basically instead of iterating over the keys of users you are
iterating over the keys of partition table,
as x is updated inside inner foorloop(so x contains the keys of partition
table).
'''
final.append(s)
Now the reason for halting is (say you have 10 keys in users dictionary).
so outer forloop will iterate 10 times and for the 10 times
Inner forloop will iterate over whole partition keys and make a copy
which is causing memory error and eventually your system gets hung due to out of memory.
I think this will work for you
store partition data in a python defaultdict(list)
from collections import defaultdict
user_key = users.keys()
part_dict = defaultdict(list)
# partition = [[key1, value], [key2, value], ....]
# store your parition data in this way (list inside list)
for index in parition:
if index[0] not in part_dict:
part_dict[index[0]] = index[1]
else:
part_dict[index[0]].append(index[1])
# part_dict = {key1:[1,2,3], key2:[1,2,3], key3:[4,5],....}
final = []
for x in user_keys:
for values in part_dict[x]:
final.append([x, values])
# if you want your result of dictionary format(I don't think it's required) then you ca use
# final.append({x:values})
# final = [{key1: 1}, {key2: 2}, ....]
# final = [[key1, 1], [key1, 2], [key1, 3], .....]
The above code is not tested, some minor changes may be required
>>> the_values = [u'abc', u'kfc', u'listproperty', u'models', u'new', u'newer', u'note', u'order', u'tag', u'test', u'type']
>>> the_keys = [1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1]
d2 = dict(zip(the_keys, the_values))
>>> d2
{1: u'type', 2: u'tag'}
Can you give me a clue why only "type" and "tag" are taken?
I am trying to sort the_values by the_keys.
I noticed that switching the order of the_values and the_keys works:
>>> d2 = dict(zip(the_values, the_keys))
>>> d2
{u'abc': 1, u'models': 2, u'note': 1, u'tag': 2, u'kfc': 2, u'newer': 1, u'listproperty': 1, u'test': 1, u'new': 1, u'type': 1, u'order': 1}
Thanks.
Keys must be unique, so using 1 and 2 as the only keys means you can only have two values associated with them.
When you're creating the dictionary, you're setting the key to correspond to a value. So first, 1 -> abc, 2 -> kfc. But then you're continually overriding the keys to give them different values. In the end, only the latest values for the keys are kept (1 -> type, 2-> tag).
As others have said, keys must be unique. In order to get around that, you must not use a dictionary.
>>> [x[1] for x in sorted(zip(the_keys, the_values), key=operator.itemgetter(0))]
[u'abc', u'listproperty', u'new', u'newer', u'note', u'order', u'test', u'type', u'kfc', u'models', u'tag']
Because a dictionary, by definition, has unique keys. (Otherwise, how would it know which value to return when you look up the key?) The dict constructor iterates through the key-value pairs and assigns the value to the corresponding key in the dictionary, overwriting the previous value for keys that are already present.