Truncate or trim a list in python - python

I have a list like this:
[{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '10.113.97.0/26'}, {'CidrIp': '10.111.0.0/22'}, {'CidrIp': '10.140.0.0/16'}, {'CidrIp': '10.141.0.0/16'}, {'CidrIp': '10.145.0.0/16'}, {'CidrIp': '10.112.0.0/26'}, {'CidrIp': '10.112.0.64/26'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'UserIdGroupPairs': []}]
Need trim only the IP's after words CidrIP, only the numbers:
10.113.97.0/26
10.111.0.0/22
10.140.0.0/16
...
How it's this possible? I tested with s.strip or map but don't get it.
Thanks a lot!

ips = data.get('IpRanges', []) # get the IpRanges list from main dict
ips = [ip['CidrIp'] for ip in ips] # iterate over Ipranges list and get value of CidrIp.
print(ips)

You can use a combination of list comprehension and string manipulation to extract only the IP addresses from the list of dictionaries. Here's an example code that should work:
data = [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '10.113.97.0/26'}, {'CidrIp': '10.111.0.0/22'}, {'CidrIp': '10.140.0.0/16'}, {'CidrIp': '10.141.0.0/16'}, {'CidrIp': '10.145.0.0/16'}, {'CidrIp': '10.112.0.0/26'}, {'CidrIp': '10.112.0.64/26'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'UserIdGroupPairs': []}]
ip_list = [ip['CidrIp'].split('/')[0] for item in data for ip in item['IpRanges']]
print(ip_list)
This returns the following:
['10.113.97.0', '10.111.0.0', '10.140.0.0', '10.141.0.0', '10.145.0.0', '10.112.0.0', '10.112.0.64']

You can use the following code:
AIM = [i["CidrIp"] for i in DATA[0].get("IpRanges")]

You can use list comprehension with linear time complexity with one for-loop
l=[{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '10.113.97.0/26'}, {'CidrIp': '10.111.0.0/22'}, {'CidrIp': '10.140.0.0/16'}, {'CidrIp': '10.141.0.0/16'}, {'CidrIp': '10.145.0.0/16'}, {'CidrIp': '10.112.0.0/26'}, {'CidrIp': '10.112.0.64/26'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'UserIdGroupPairs': []}]
ips=[x['CidrIp'] for x in l[0]['IpRanges']]
print(ips)
['10.113.97.0/26', '10.111.0.0/22', '10.140.0.0/16', '10.141.0.0/16', '10.145.0.0/16', '10.112.0.0/26', '10.112.0.64/26']
if you are looking for this:
ips=[x['CidrIp'].split('/')[0] for x in l[0]['IpRanges']]
print(ips)
['10.113.97.0', '10.111.0.0', '10.140.0.0', '10.141.0.0', '10.145.0.0', '10.112.0.0', '10.112.0.64']

Assume that the data object is store into variable called data
data = [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '10.113.97.0/26'}, {'CidrIp': '10.111.0.0/22'}, {'CidrIp': '10.140.0.0/16'}, {'CidrIp': '10.141.0.0/16'}, {'CidrIp': '10.145.0.0/16'}, {'CidrIp': '10.112.0.0/26'}, {'CidrIp': '10.112.0.64/26'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'UserIdGroupPairs': []}]
Now, use list comprehension to extract all IP Address
ip_address_list = [ip['CidrIp'] for ip in data[0]['IpRanges']]
The output result is
['10.113.97.0/26', '10.111.0.0/22', '10.140.0.0/16', '10.141.0.0/16', '10.145.0.0/16', '10.112.0.0/26', '10.112.0.64/26']
If you want to get only Address
ip_address_list = [ip['CidrIp'].split('/')[0] for ip in data[0]['IpRanges']]
The result is
['10.113.97.0', '10.111.0.0', '10.140.0.0', '10.141.0.0', '10.145.0.0', '10.112.0.0', '10.112.0.64']
If you want to get only Subnet Mask
subnet_mask_list = [int(ip['CidrIp'].split('/')[1]) for ip in data[0]['IpRanges']]
The result is
[26, 22, 16, 16, 16, 26, 26]
You can also use ipaddress library to resolve IP Address and separate into Address and Subnet Mask
import ipaddress
for ip in data[0]['IpRanges']:
net = ipaddress.ip_network(ip['CidrIp'])
print('Address :', net.network_address, ' Subnet Mask :', net.netmask)
The output result
Address : 10.113.97.0 Subnet Mask : 255.255.255.192
Address : 10.111.0.0 Subnet Mask : 255.255.252.0
Address : 10.140.0.0 Subnet Mask : 255.255.0.0
Address : 10.141.0.0 Subnet Mask : 255.255.0.0
Address : 10.145.0.0 Subnet Mask : 255.255.0.0
Address : 10.112.0.0 Subnet Mask : 255.255.255.192
Address : 10.112.0.64 Subnet Mask : 255.255.255.192

Related

Phython: How to extract a number

i just started up using phython & i try to help my dad to develop a small program:
from a query i get a retun that i converted into a dict as i want to extract the 'last_price': '1704.50'. I tried it with find, count ... but it seems that i'm running into a wall.
here is the string & it looks like that the bracket makes it harder to extract:
dict_items([('ret_code', 0), ('ret_msg', 'OK'), ('ext_code', ''), ('ext_info', ''), ('result', [{'symbol': 'ETHUSDT', 'bid_price': '1701.8', 'ask_price': '1702', 'last_price': '1704.50', 'last_tick_direction': 'PlusTick', 'prev_price_24h': '1647.55', 'price_24h_pcnt': '0.034566', 'high_price_24h': '1710.55', 'low_price_24h': '1620.40', 'prev_price_1h': '1679.40', 'price_1h_pcnt': '0.014945', 'mark_price': '1702.51', 'index_price': '1702.38', 'open_interest': 150155.81, 'open_value': '0.00', 'total_turnover': '54418340521.33', 'turnover_24h': '63239638.53', 'total_volume': 58525803.73, 'volume_24h': 37976.79, 'funding_rate': '0.0001', 'predicted_funding_rate': '0.0001', 'next_funding_time': '2022-08-25T08:00:00Z', 'countdown_hour': 1, 'delivery_fee_rate': '', 'predicted_delivery_price': '', 'delivery_time': ''}]), ('time_now', '1661411154.330653')])
Any idea is more than welcome
Thanks
Alice
Hope I'm uderstanding it right but this works for me:
d=dict([('ret_code', 0), ('ret_msg', 'OK'), ('ext_code', ''), ('ext_info', ''), ('result', [{'symbol': 'ETHUSDT', 'bid_price': '1701.8', 'ask_price': '1702', 'last_price': '1704.50', 'last_tick_direction': 'PlusTick', 'prev_price_24h': '1647.55', 'price_24h_pcnt': '0.034566', 'high_price_24h': '1710.55', 'low_price_24h': '1620.40', 'prev_price_1h': '1679.40', 'price_1h_pcnt': '0.014945', 'mark_price': '1702.51', 'index_price': '1702.38', 'open_interest': 150155.81, 'open_value': '0.00', 'total_turnover': '54418340521.33', 'turnover_24h': '63239638.53', 'total_volume': 58525803.73, 'volume_24h': 37976.79, 'funding_rate': '0.0001', 'predicted_funding_rate': '0.0001', 'next_funding_time': '2022-08-25T08:00:00Z', 'countdown_hour': 1, 'delivery_fee_rate': '', 'predicted_delivery_price': '', 'delivery_time': ''}]), ('time_now', '1661411154.330653')])
d['result'][0]['last_price']
gives the number. Notice the [0] due to the "[ ]" you mentioned.
If you are dealing with texts, regex might be more appropriate:
import re
text = """dict_items([('ret_code', 0), ('ret_msg', 'OK'), ('ext_code', ''), ('ext_info', ''), ('result', [{'symbol': 'ETHUSDT', 'bid_price': '1701.8', 'ask_price': '1702', 'last_price': '1704.50', 'last_tick_direction': 'PlusTick', 'prev_price_24h': '1647.55', 'price_24h_pcnt': '0.034566', 'high_price_24h': '1710.55', 'low_price_24h': '1620.40', 'prev_price_1h': '1679.40', 'price_1h_pcnt': '0.014945', 'mark_price': '1702.51', 'index_price': '1702.38', 'open_interest': 150155.81, 'open_value': '0.00', 'total_turnover': '54418340521.33', 'turnover_24h': '63239638.53', 'total_volume': 58525803.73, 'volume_24h': 37976.79, 'funding_rate': '0.0001', 'predicted_funding_rate': '0.0001', 'next_funding_time': '2022-08-25T08:00:00Z', 'countdown_hour': 1, 'delivery_fee_rate': '', 'predicted_delivery_price': '', 'delivery_time': ''}]), ('time_now', '1661411154.330653')])"""
last_price_pattern = r"'last_price'\s*:\s*'(\d*\.\d*)'"
last_price = float(re.findall(last_price_pattern, text)[0])
print(last_price)
If you're dealing with a list, then simple indexing will suffice:
raw_data = [('ret_code', 0), ('ret_msg', 'OK'), ('ext_code', ''), ('ext_info', ''), ('result', [{'symbol': 'ETHUSDT', 'bid_price': '1701.8', 'ask_price': '1702', 'last_price': '1704.50', 'last_tick_direction': 'PlusTick', 'prev_price_24h': '1647.55', 'price_24h_pcnt': '0.034566', 'high_price_24h': '1710.55', 'low_price_24h': '1620.40', 'prev_price_1h': '1679.40', 'price_1h_pcnt': '0.014945', 'mark_price': '1702.51', 'index_price': '1702.38', 'open_interest': 150155.81, 'open_value': '0.00', 'total_turnover': '54418340521.33', 'turnover_24h': '63239638.53', 'total_volume': 58525803.73, 'volume_24h': 37976.79, 'funding_rate': '0.0001', 'predicted_funding_rate': '0.0001', 'next_funding_time': '2022-08-25T08:00:00Z', 'countdown_hour': 1, 'delivery_fee_rate': '', 'predicted_delivery_price': '', 'delivery_time': ''}]), ('time_now', '1661411154.330653')]
last_price = float(raw_data[4][1][0]['last_price'])
print(last_price)

Compare values from multiple dictionaries

I have two lists of dictionaries and a tuple:
vrfs = [
{'default_rd': '<not set>',
'interfaces': ['Gi0/0'],
'name': 'Mgmt-vrf',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:510',
'interfaces': ['503', '510', '515'],
'name': 'VLAN1',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:993',
'interfaces': ['993'],
'name': 'VLAN2',
'protocols': 'ipv4,ipv6'}
]
my_dict = [
{'Device Name': '',
'Hostname': 'switch1',
'IP Address': '',
'Interface Number': 'Gi1/0/2',
'MAC': 'A0:B1:C2:D3:E4:F5',
'VLAN': '503'},
{'Device Name': '',
'Hostname': 'switch1',
'IP Address': '',
'Interface Number': 'Gi1/0/3',
'MAC': 'A1:B2:C3:D4:E5:F6',
'VLAN': '510'},
{'Device Name': '',
'Hostname': 'switch1',
'IP Address': '',
'Interface Number': 'Gi1/0/4',
'MAC': 'A2:B3:C4:D5:E6:F7',
'VLAN': '515'},
{'Device Name': '',
'Hostname': 'switch1',
'IP Address': '',
'Interface Number': 'Gi1/0/5',
'MAC': 'A3:B4:C5:D6:E7:F8',
'VLAN': '993'},
{'Device Name': '',
'Hostname': 'switch1',
'IP Address': '',
'Interface Number': 'Gi1/0/6',
'MAC': 'A4:B5:C6:D7:E8:F9',
'VLAN': '750'}
]
vlans = ('Gi0/0', '503', '510', '515', '993')
And I need to iterate through my_dict but if my_dict["VLAN"] is in vlans tuple then I need search in vrfs and return the vrfs["name"].
So something like:
if vlan in vlans:
print(f"show ip arp vrf {vrfs['name']} {my_dict}['MAC']")
else:
print(f"show ip arp {my_dict}['MAC']")
How would I accomplish this?
Your question is not clear but I do what I understand.
for a in my_dict:
if a['VLAN'] in vlans:
for i in vrfs:
if a['VLAN'] in i['interfaces']:
print(i['name'])
OUTPUT:
VLAN1
VLAN1
VLAN1
VLAN2
If you make a lookup dict mapping interfaces to name from vrfs, then you can do this in a single list comprehension.
vrfs_lookup = {key: item['name'] for item in vrfs for key in item['interfaces']}
names = [vrfs_lookup[item['VLAN']] for item in my_dict if item['VLAN'] in vlans]
This will give you a list of names:
['VLAN1', 'VLAN1', 'VLAN1', 'VLAN2']

moto not mocking ec2.describe_security_groups function call

import boto3
....
#mock_ec2
def test_mocking_getting_security_groups(self):
region = 'us-east-2'
vpc_security_group_id = 'default'
session = boto3.Session(profile_name=profile)
ec2_client = session.client('ec2', region)
print(ec2_client.describe_security_groups())
print(ec2_client.describe_security_groups(GroupIds=['sg-3e2bcf04']))
I have this test case and the first prints
{'SecurityGroups': [{'Description': 'default group', 'GroupName': 'default', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-0b13b4ba', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': []}, {'Description': 'default VPC security group', 'GroupName': 'default', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-df20018b', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': [], 'VpcId': 'vpc-1940c2c1'}], 'ResponseMetadata': {'RequestId': '59dbff89-35bd-4eac-99ed-be587EXAMPLE', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}
which seems fine, seems like it's the properly mocked response. But then: ec2_client.describe_security_groups(GroupIds=['sg-3e2bcf04']) fails
E botocore.exceptions.ClientError: An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group '{'sg-3e2bcf04'}' does not exist
Is there something else I need to mock out?
EDIT:
It seems like it generates a non predictable random GroupID at every run. Any idea how to lock it down?
You may need to create one SG and can describe the created one.
source
import boto3
from moto import mock_ec2
#mock_ec2
def test_mocking_getting_security_groups():
region = 'us-east-2'
vpc_security_group_id = 'default'
session = boto3.Session(profile_name='shakeel_aws')
ec2_client = session.client('ec2', region)
sg = ec2_client.create_security_group(GroupName="test-sg", Description="Test SG")
print(sg["GroupId"])
print(ec2_client.describe_security_groups())
print(ec2_client.describe_security_groups(GroupIds=[sg["GroupId"]]))
test_mocking_getting_security_groups()
Output:
sg-27a9b9cf
{'SecurityGroups': [{'Description': 'default group', 'GroupName': 'default', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-7af61a21', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': []}, {'Description': 'Test SG', 'GroupName': 'test-sg', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-27a9b9cf', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': []}, {'Description': 'default VPC security group', 'GroupName': 'default', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-4ec8ebd5', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': [], 'VpcId': 'vpc-b1373745'}], 'ResponseMetadata': {'RequestId': '59dbff89-35bd-4eac-99ed-be587EXAMPLE', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}
{'SecurityGroups': [{'Description': 'Test SG', 'GroupName': 'test-sg', 'IpPermissions': [], 'OwnerId': '123456789012', 'GroupId': 'sg-27a9b9cf', 'IpPermissionsEgress': [{'IpProtocol': '-1', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'UserIdGroupPairs': []}], 'Tags': []}], 'ResponseMetadata': {'RequestId': '59dbff89-35bd-4eac-99ed-be587EXAMPLE', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

How can I convert a JSON data (from API) into python data?

Hey guys i´m traying to get data from API stock market.
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
print("Recibo mensajes del servidor...")
socket.connect("tcp://XXXXXXXXXXXXXXXXXX")
socket.setsockopt_string(zmq.SUBSCRIBE, u'')
while True:
JSON = socket.recv_json()
print(JSON)
And recive data like this:
{'X': {'MDReqId': 'HUB22_1533207696768', 'MDIncGrp': [{'offer': {'OrderID':
'', 'SettlType': '3', 'MDEntrySeller': '', 'Precio': '435',
'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 2000.0,
'MDUpdateAction': '2', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C',
'MDEntryBuyer': '', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}}],
'MDBookType': 2}}
{'X': {'MDReqId': 'HUB22_1533207696768', 'MDIncGrp': [{'bid': {'OrderID': '',
'SettlType': '3', 'MDEntrySeller': '', 'Precio': '410', 'MDEntryPositionNo':
'2', 'SettlDate': '', 'MDEntrySize': 24.0, 'MDUpdateAction': '0',
'MDEntryTime': '10:37:56', 'Symbol': 'BA.C', 'MDEntryBuyer': '200',
'NumberOfOrders': '', 'MDEntryDate': '20180802'}}, {'offer': {'OrderID': '',
'SettlType': '3', 'MDEntrySeller': '046', 'Precio': '450',
'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 2000.0,
'MDUpdateAction': '0', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C',
'MDEntryBuyer': '200', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}},
{'bid': {'OrderID': '', 'SettlType': '3', 'MDEntrySeller': '046', 'Precio':
'433', 'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 10.0,
'MDUpdateAction': '0', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C',
'MDEntryBuyer': '262', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}}],
'MDBookType': 3}}
My question is:
How can I convert a JSON data (from API) into python data?
You already have JSON (well, a Python dict but Python folks think they're the same thing)!
Run this experiment:
while True:
json = socket.recv_json()
print(json['X'])
x = json['X'] # now `x` is the "same" as json['X']
print(x['MDReqId']) # this is equivalent to print(json['X']['MDReqId'])
md_req_id = x['MDReqId']
print(md_req_id) # should output `HUB22_1533207696768`
The results you are getting from recv_json are already a built-in Python type (dict). So you could do something like:
JSON['x']

Extracting a key from a dictionary to another dictionary in Python

I have a big python dictionary. One of its keys has another dictionary as the value. I want to create a new dictionary using the values and then delete the key from my original dictionary.
Is there any function to export the values into another dictionary? To delete I know I can use the .pop() function. I tried googling but wasn't successful.
This is the dictionary. I used stars to block out sensitive information. The key I need is billing_address, which has another dictionary as the values:
{
'shipping_cost_tax': '0.0000',
'refunded_amount': '0.0000',
'external_source': None,
'discount_amount': '0.0000',
'base_wrapping_cost': '0.0000',
'shipping_cost_tax_class_id': 2,
'payment_method': 'PayPal',
'handling_cost_ex_tax': '0.0000',
'store_credit_amount': '0.0000',
'shipping_cost_inc_tax': '11.0000',
'handling_cost_tax_class_id': 2,
'currency_id': 1,
'payment_status': 'captured',
'subtotal_ex_tax': '99.0000',
'total_inc_tax': '11.0000',
'handling_cost_inc_tax': '0.0000',
'total_ex_tax': '11.0000',
'is_deleted': False,
'status_id': 5,
'id': 614534,
'shipping_cost_ex_tax': '11.0000',
'date_shipped': '',
'order_source': 'www',
'status': 'Cancelled',
'handling_cost_tax': '0.0000',
'items_total': 3,
'wrapping_cost_tax': '0.0000',
'date_created': 'Wed,
09 Jul 2014 12:22:17 +0000',
'total_tax': '0.0000',
'order_is_digital': False,
'date_modified': 'Thu,
30 Oct 2014 02:34:07 +0000',
'geoip_country': 'Australia',
'base_shipping_cost': '11.0000',
'payment_provider_id': '**************',
'staff_notes': '',
'default_currency_id': 1,
'currency_code': 'AUD',
'currency_exchange_rate': '1.0000000000',
'coupon_discount': '99.0000',
'customer_message': '',
'subtotal_inc_tax': '99.0000',
'gift_certificate_amount': '0.0000',
'items_shipped': 0,
'default_currency_code': 'AUD',
'customer_id': 1,
'geoip_country_iso2': 'AU',
'ip_address': '124.168.160.136',
'shipping_address_count': 1,
'wrapping_cost_ex_tax': '0.0000',
'base_handling_cost': '0.0000',
'wrapping_cost_tax_class_id': 3,
'ebay_order_id': '0',
'wrapping_cost_inc_tax': '0.0000',
'billing_address': {
'state': '*******',
'street_1': '*************',
'street_2': '',
'country_iso2': 'AU',
'last_name': '************',
'company': '***************',
'country': 'Australia',
'first_name': '*********',
'email': '***************',
'phone': '*************',
'city': '*************',
'zip': '************'
},
'subtotal_tax': '0.0000'
}
EDIT:
def popAndMergeDicts(line):
tempDict = line['billing_address']
del line['billing_address']
for i in tempDict:
line[i] = tempDict[i]
print(line)
def process_file(filename):
lines = tuple(open(filename))
for line in lines[0:1]:
popAndMergeDicts(line)
process_file('allOrdersData')
allOrdersData is a file where I have many dictionaries like the one I posted before, one in each line. I get the following error when I try to run it:
TypeError: string indices must be integers
EDIT 2:
Nevermind, got it working with ast.literal_eval:
import ast
def popAndMergeDicts(line):
dictLine = ast.literal_eval(line)
tempDict = dictLine['billing_address']
del dictLine['billing_address']
for i in tempDict:
dictLine[i] = tempDict[i]
print(dictLine)
def process_file(filename):
lines = tuple(open(filename))
for line in lines[0:]:
popAndMergeDicts(line)
process_file('allOrdersData')
Just use .pop(): it returns the value it pops. Eg,
#!/usr/bin/env python
import pprint
big_dict = {
'shipping_cost_tax': '0.0000',
'refunded_amount': '0.0000',
#etc
'billing_address': {
'state': '*******',
'street_1': '*************',
'street_2': '',
'country_iso2': 'AU',
#etc
},
'subtotal_tax': '0.0000'
}
print 'Before'
pprint.pprint(big_dict, indent=4)
bill_dict = big_dict.pop('billing_address')
print '\nBill dict'
pprint.pprint(bill_dict, indent=4)
print '\nAfter'
pprint.pprint(big_dict, indent=4)
output
Before
{ 'billing_address': { 'country_iso2': 'AU',
'state': '*******',
'street_1': '*************',
'street_2': ''},
'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'subtotal_tax': '0.0000'}
Bill dict
{ 'country_iso2': 'AU',
'state': '*******',
'street_1': '*************',
'street_2': ''}
After
{ 'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'subtotal_tax': '0.0000'}
To keep the keys/values in the original dictionary, instead of creating a new one, you can do what Marichyasana suggests:
bill_dict = big_dict.pop('billing_address')
for k in bill_dict:
big_dict[k] = bill_dict[k]
del bill_dict
print '\nAfter'
pprint.pprint(big_dict, indent=4)
output
After
{ 'country_iso2': 'AU',
'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'state': '*******',
'street_1': '*************',
'street_2': '',
'subtotal_tax': '0.0000'}
I've also deleted the temporary bill_dict. That's not strictly necessary, as bill_dict will automatically be deleted once it goes out of scope.
If you just want to reference the "sub-dictionary", you could simply use (where d is your original dictionary):
billing1 = d['billing_address']
If you want a distinct, separate copy, you could use any of the following:
billing2 = dict(d['billing_address'])
billing3 = d['billing_address'].copy()
billing4 = copy.copy(d['billing_address']) # after import copy
Changes to values in billing1 will be reflected in your original dictionary. Changes to values in the other three will not be reflected in your original dictionary.
If you want to delete the billing_address key also (like you suggest in your question but backpedal on in your comments), then use one of the above approaches first, followed by:
del d['billing_address']
Or, as one step, if you're committed to deleting the key from your original dictionary, use dict.pop()
billing5 = d.pop('billing_address')
Let 'a' be the name of the dictionary
Let 'b' be the name of the billing_address dictionary
b=a['billing_address']
del a['billing_address']
for i in b:
a[i]=b[i]
ans = {key:val for key, val in input_dict.pop('billing_address').items()}
dict1 = {'shipping_cost_tax': '0.0000', 'refunded_amount': '0.0000', 'external_source': None, 'discount_amount': '0.0000', 'base_wrapping_cost': '0.0000', 'shipping_cost_tax_class_id': 2, 'payment_method': 'PayPal', 'handling_cost_ex_tax': '0.0000', 'store_credit_amount': '0.0000', 'shipping_cost_inc_tax': '11.0000', 'handling_cost_tax_class_id': 2, 'currency_id': 1, 'payment_status': 'captured', 'subtotal_ex_tax': '99.0000', 'total_inc_tax': '11.0000', 'handling_cost_inc_tax': '0.0000', 'total_ex_tax': '11.0000', 'is_deleted': False, 'status_id': 5, 'id': 614534, 'shipping_cost_ex_tax': '11.0000', 'date_shipped': '', 'order_source': 'www', 'status': 'Cancelled', 'handling_cost_tax': '0.0000', 'items_total': 3, 'wrapping_cost_tax': '0.0000', 'date_created': 'Wed, 09 Jul 2014 12:22:17 +0000', 'total_tax': '0.0000', 'order_is_digital': False, 'date_modified': 'Thu, 30 Oct 2014 02:34:07 +0000', 'geoip_country': 'Australia', 'base_shipping_cost': '11.0000', 'payment_provider_id': '**************', 'staff_notes': '', 'default_currency_id': 1, 'currency_code': 'AUD', 'currency_exchange_rate': '1.0000000000', 'coupon_discount': '99.0000', 'customer_message': '', 'subtotal_inc_tax': '99.0000', 'gift_certificate_amount': '0.0000', 'items_shipped': 0, 'default_currency_code': 'AUD', 'customer_id': 1, 'geoip_country_iso2': 'AU', 'ip_address': '124.168.160.136', 'shipping_address_count': 1, 'wrapping_cost_ex_tax': '0.0000', 'base_handling_cost': '0.0000', 'wrapping_cost_tax_class_id': 3, 'ebay_order_id': '0', 'wrapping_cost_inc_tax': '0.0000', 'billing_address': {'state': '*******', 'street_1': '*************', 'street_2': '', 'country_iso2': 'AU', 'last_name': '************', 'company': '***************', 'country': 'Australia', 'first_name': '*********', 'email': '***************', 'phone': '*************', 'city': '*************', 'zip': '************'}, 'subtotal_tax': '0.0000'}
print {'billing_address': dict1['billing_address']}

Categories

Resources