Python - dict full of identical values - python

Really can't get out of this...
Here's my python code:
for i in range(len(realjson)) :
store["Store"]={
"id" :realjson[i]['id'].strip(),
"retailer_id" :RETAILER_ID,
"name" :find(realjson[i]["title"],">","<").strip(),
"address" :realjson[i]["address"].strip(),
"city" :realjson[i]["address"].split(",")[-4].strip(),
"province" :realjson[i]["address"].split(",")[-3].strip(),
"group" :realjson[i]["address"].split(",")[-1].strip(),
"zip" :realjson[i]["address"].split(",")[-2].strip(),
"url" :"http://blabla.com?id="+realjson[i]["id"].strip(),
"lat" :realjson[i]["lat"].strip(),
"lng" :realjson[i]["lon"].strip(),
"phone" :realjson[i]["telephone_number"].replace("<br />Phone Number: ","").strip()
}
stores.append(store)
print stores[i]
When I print the list inside the for loop it works correctly.
Otherwise when I print the array outside the loop like this:
print storesit contains only the last element that I've appended repeated for the entire length of the list.
Do you have some advice to help me!
Thank you.

You reuse a mutable object in your loop:
store['Store']
Create a new copy in the loop instead:
newstore = store.copy()
newstore['Store'] = { ... }

store["Store"]={ ... }
if you expect this line to create new dictionary with just one key, then what you actually want is
store = {"Store": { ... }}

Related

How to get a key from inside another key in python

Hey does anybody know how I would go about getting the value of a key which is already inside another key like this:
a = {"fruit":[{"oranges":['10']},{"apples":['11']}]}
print(a.get("fruit"))
I can get the value of "fruit" but how would I get the value of "oranges".
Thank you for any help in advance.
Let's format your dictionary and clearly see what you have:
a = {
"fruit": [
{
"oranges": ['10']
},
{
"apples": ['11']
}
]
}
So, a.get('fruit') gives you a list, which elements can be accessed with indexes.
So a['fruit'][0] gives you
{
"oranges": ['10']
}
and a['fruit'][1] gives you
{
"apples": ['11']
}
So in order to get the value of oranges you should go with:
a['fruit'][0]['oranges']
which will give you: ['10']. ['10'] is a list of its own. If you want to get only the value, you can do:
a['fruit'][0]['oranges'][0]
You just have to access the first element of the list inside fruits, and then access the key inside
print(a['fruit'][0]['oranges']

Python - append JSON into main branch

Maybe I am too stuck to see the simple solution for the following problem:
Given:
import json
a = {
"24631331976_defa3bb61f_k.jpg668058":{
"regions": {
"0": {},
"1": {}
}
}
}
b = {
"16335852991_f55de7958d_k.jpg1767935":{
"regions": {
"0": {}
}
}
}
I want to append them in order to get the following output.
enter image description here
Thanks to Daniel Hepper and SegFault, the problem could be solved with:
a.update(b)
c = {}
c.update(a)
c.update(b)
Alternatively, if you are fine with modifying a:
a.update(b)
Note that your code uses Python dictionaries, not JSON strings.
You cannot 'append' a dict to another one, simply because the append add element to the end of an ordered list of elements.
dicts don't have the notion of order, fist or last element. Thus no append for dict.
The action you want to do is merging two dicts, and you can do that using the update method defined for the dict type.
a.update(b)
PS: that will modify the dict a

Deleting a key from a dictionary that is in a list of dictionaries

I have a list of dictionaries generated by:
r=requests.get(url, headers={key:password})
import_data_list.append(r.json())
I want to delete the first key from these dictionaries. I know I can delete the dictionaries in the list with:
del import_data_list[0]
But how do I delete a key from the dictionary in the list, rather than deleting the whole dictionary.
I tried something like:
del import_data_list[0["KEY"]]
Obviously it doesnt work!
Any help would be much appreciated and sorry if its a dumb question. Still learning!
If you want to delete the first key (you don't know its name, you just know it is the first one) from these dictionaries, I suggest you to loop over the dictionaries of the list. You can use list(d.keys())[0] or even list(d)[0] to get the first key of a dictionary called d.
Here is an example:
for d in import_data_list:
k = list(d)[0] # get the first key
del d[k] # delete it from the dictionary
print(import_data_list)
You can also do it with one-lined style using a list comprehension, which I find quite smart too. In this case you also retrieve the values of the first keys in a list, which might be useful:
r = [d.pop(list(d)[0]) for d in import_data_list]
print(import_data_list)
Note that it works only with python version >= 3.6 (but not with version <= 3.5 because dictionaries are not ordered)
Assume you have this list of dictionaries.
myList = [
{
"Sub1List1" : "value",
"Sub2List1" : "value",
"Sub3List1" : "value",
"Sub4List1" : "value"
},
{
"Sub1List2" : "value",
"Sub2List2" : "value",
"Sub3List2" : "value",
"Sub4List2" : "value"
},
{
"Sub1List3" : "value",
"Sub2List3" : "value",
"Sub3List3" : "value",
"Sub4List3" : "value"
}
]
Now, if you want to delete key Sub1List1 from the first list, you can do this by using :
del myList[0]["Sub1List1"]
Use the command:
del dictionaryName[KEY]

Parsing dynamically changing json file and store it to dict in python

I have dynamically changing json file (not the entire file changes dynamically, its just at one point which I will specify below) and I need to iterate using for loop at that point (where it changed dynamically) so that I can grab required elements inside that bracket in json file. Below is json snippet what it looks like.
"A" : {
"uni/aa/bb" (----> This changes randomly): [ {
"Name" : "cc",
"Id" : "1",
}, {
"Name" : "cc",
"Id" : "1",
} ]
}
I used re.search to match the pattern I get at that point. But no luck. I need to store Name and Id values ultimately. Any suggestions?
resp = json.loads(resp) ---> This gives me above mentioned json output
Here are the sample of codes I am trying.
for k in resp['A']:
for v in k['uni/aa/bb']: #---> TypeError: string indices must be integers
for k in resp['A']:
m = re.search('uni/(.*)') #--> Because this is changing dynamically
if m:
name = str(m['Name']) #---> TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
If it the case that you always want to know the string key that belongs to the child of "A" object and don't mind removing the item from json, you can try poping the thing. Like this: key, value = resp["A"].popitem(). From this key, you can get those uni/aa/bb strings, whatever it maybe. And after that you can also traverse that child further down the depth like this: resp["A"][key][0]["Name"]. Reference.
Sample code.
Another approach could be like the following. Instead of for v in k['uni/aa/bb']: use this: for key, value in k.items(): in case of python3.x or for key, value in k.iteritems(): for python2.x. Reference.
Sample code.

Named dictionary in python

I did some research on how to use named array from PHP in python, while i found the following code example as they said can be done with dictionary.
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
Source: Portion of code getting from here
Reference: Python references
But how could i adding a new value through a loop? While the references shown on how to adding single value by simply shows['key']="value" but i can't linking both of them. Can anyone please show me how to add the value into this dictionary through a loop?
For example:
for message in messages:
myvariable inside having two field
- Message
- Phone number
Update
May i know how could i loop them out to display after aped list into dictionary? Thanks!
You should be adding the dictionary into an array like :
friends = []
for message in messages:
dict = {"message" : message.message, "phone" : message.phone }
friends.append(dict)
to loop again, you can do it this way :
for friend in friends:
print "%s - %s" % (friend["message"], friend["phone"])
Effectively your example is a list of dictionaries, in PHP terms array of associative arrays.
To add an item you can do:
shows.append({ "id" : 3, "name" : "House M.D."})
[] denotes a list, or an array.
{} denotes a dictionary or an associative array.
In short, you can do (list comprehension)
message_informations = [{"message": m.message, "phone": m.phone} for m in messages]
If you want to assing an id for each message_information and store in a dictionary (dict comprehension)
{_id: {"message": m.message, "phone": m.phone} for _id, m in enumerate(messages)}

Categories

Resources